-
Notifications
You must be signed in to change notification settings - Fork 0
/
simplate.go
54 lines (45 loc) · 1.54 KB
/
simplate.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
package simplate
import (
"bytes"
"html/template"
"io"
"github.com/chalvern/sugar"
)
// InitTemplate init templates
func InitTemplate() error {
simplateViewPathTemplates = make(map[string]*template.Template)
return BuildTemplate(defaultViewsPath)
}
// ExecuteTemplate execute template with default layout file.
func ExecuteTemplate(wr io.Writer, bodyName string, data map[string]interface{}) error {
if layout, ok := data["layout"]; ok {
return ExecuteViewPathTemplateWithLayout(wr, layout.(string), bodyName, data)
}
return ExecuteViewPathTemplateWithLayout(wr, defaultLayoutFile, bodyName, data)
}
// ExecuteViewPathTemplateWithLayout excute template with layout
func ExecuteViewPathTemplateWithLayout(wr io.Writer, layoutName, bodyName string, data map[string]interface{}) error {
// body
var buf bytes.Buffer
ExecuteViewPathTemplate(&buf, bodyName, data)
data["LayoutContent"] = template.HTML(buf.String())
// layout
return ExecuteViewPathTemplate(wr, layoutName, data)
}
// ExecuteViewPathTemplate applies the template with name and from specific viewPath to the specified data object,
// writing the output to wr.
func ExecuteViewPathTemplate(wr io.Writer, name string, data interface{}) error {
if t, ok := simplateViewPathTemplates[name]; ok {
var err error
if t.Lookup(name) != nil {
err = t.ExecuteTemplate(wr, name, data)
} else {
err = t.Execute(wr, data)
}
if err != nil {
sugar.Error("template Execute err:", err)
}
return err
}
panic("can't find templatefile in the path:" + defaultViewsPath + "/" + name)
}