-
Notifications
You must be signed in to change notification settings - Fork 0
/
kira_view.go
85 lines (75 loc) · 2.08 KB
/
kira_view.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
package kira
import (
"encoding/json"
"fmt"
"html/template"
"path/filepath"
"strings"
)
// parse the view and return the view template and the view data.
func parseView(c *Context, temps string, data ...interface{}) (*template.Template, error) {
fileSuffix := c.Config().GetString("views.file_suffix", ".go.html")
viewPath := c.Config().GetString("views.path", "./app/views/")
templates := strings.Split(temps, "|")
// hold all templates
var templatesFiles []string
baseTemplate := filepath.Base(templates[0]) + fileSuffix
// loop throw all templates
for _, temp := range templates {
tmplPath := filepath.Join(viewPath, temp+fileSuffix)
if !c.ViewExists(temp) {
return nil, fmt.Errorf("kira: template %s not exits", tmplPath)
}
templatesFiles = append(templatesFiles, tmplPath)
}
// parse templates
template, err := template.New(baseTemplate).Funcs(viewFuncs(c)).ParseFiles(templatesFiles...)
if err != nil {
return nil, err
}
return template, nil
}
func parseViewData(data ...interface{}) interface{} {
if len(data) > 0 {
return data[0]
}
return nil
}
// default views functions.
func viewFuncs(ctx *Context) template.FuncMap {
return template.FuncMap{
"env": func() string {
return ctx.Env()
},
"data": func(key string) interface{} {
return ctx.GetData(key)
},
"config": func(key string) interface{} {
return ctx.Config().Get(key)
},
"url": func() string {
return ctx.Request().URL.Path
},
"join": func(s ...string) string {
// first arg is sep, remaining args are strings to join
return strings.Join(s[1:], s[0])
},
"partial": func(filename string, data ...interface{}) (template.HTML, error) {
st, err := ctx.ViewToString(filename, data...)
if err != nil {
return "", err
}
return template.HTML(st), nil
},
"json": func(v interface{}) template.JS {
js, _ := json.Marshal(v)
return template.JS(js)
},
"html": func(value interface{}) template.HTML {
return template.HTML(fmt.Sprint(value))
},
"htmlEscape": func(value interface{}) string {
return template.HTMLEscapeString(fmt.Sprint(value))
},
}
}