-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtemplate.go
87 lines (65 loc) · 1.52 KB
/
template.go
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package stdapi
import (
"bytes"
"fmt"
"html/template"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/pkg/errors"
)
var (
templates FileSystem
templateHelpers TemplateHelpers
)
type TemplateHelpers func(c *Context) template.FuncMap
type FileSystem http.FileSystem
func LoadTemplates(files FileSystem, helpers TemplateHelpers) {
templates = files
templateHelpers = helpers
}
func TemplateExists(path string) bool {
_, err := templates.Open(path)
return !os.IsNotExist(err)
}
func RenderTemplate(c *Context, path string, params interface{}) error {
return RenderTemplatePart(c, path, "main", params)
}
func RenderTemplatePart(c *Context, path, part string, params interface{}) error {
files := []string{}
files = append(files, "layout.tmpl")
parts := strings.Split(filepath.Dir(path), "/")
for i := range parts {
files = append(files, filepath.Join(filepath.Join(parts[0:i+1]...), "layout.tmpl"))
}
files = append(files, fmt.Sprintf("%s.tmpl", path))
ts := template.New(part)
if templateHelpers != nil {
ts = ts.Funcs(templateHelpers(c))
}
for _, f := range files {
fd, err := templates.Open(f)
if os.IsNotExist(err) {
continue
}
if err != nil {
return err
}
data, err := ioutil.ReadAll(fd)
if err != nil {
return err
}
if _, err := ts.Parse(string(data)); err != nil {
return errors.WithStack(err)
}
}
var buf bytes.Buffer
if err := ts.Execute(&buf, params); err != nil {
return errors.WithStack(err)
}
io.Copy(c, &buf)
return nil
}