forked from lalluviamola/web-blog
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtemplates.go
More file actions
44 lines (37 loc) · 1.02 KB
/
templates.go
File metadata and controls
44 lines (37 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package main
import (
"bytes"
"html/template"
"io"
"io/ioutil"
"path/filepath"
)
var (
templates *template.Template
)
func loadTemplates() {
pattern := filepath.Join("www", "tmpl", "*.tmpl.html")
templates = template.Must(template.ParseGlob(pattern))
}
func execTemplateToFile(path string, templateName string, model interface{}) error {
var buf bytes.Buffer
err := templates.ExecuteTemplate(&buf, templateName, model)
must(err)
err = ioutil.WriteFile(path, buf.Bytes(), 0644)
return err
}
func execTemplateToWriter(name string, data interface{}, w io.Writer) error {
loadTemplates() // TODO: only reload when changed
return templates.ExecuteTemplate(w, name, data)
}
func execTemplate(path string, tmplName string, d interface{}, w io.Writer) error {
// this code path is for the preview on demand server
if w != nil {
return execTemplateToWriter(tmplName, d, w)
}
// this code path is for generating static files
netPath := wwwPath(path)
err := execTemplateToFile(netPath, tmplName, d)
must(err)
return nil
}