-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathtemplates.go
73 lines (65 loc) · 1.44 KB
/
templates.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
package main
import (
"errors"
"fmt"
"github.com/foolin/goview"
"github.com/foolin/goview/supports/ginview"
"github.com/gin-gonic/gin"
"html/template"
)
func initTemplates(r *gin.Engine, config *Config) {
r.HTMLRender = ginview.New(goview.Config{
Root: fmt.Sprintf("tmpl/%s", config.theme),
Extension: ".tmpl",
Partials: []string{"sidebar"},
Funcs: createFuncMap(),
DisableCache: config.disableCache,
})
}
func toHTML(s string) template.HTML {
return template.HTML(s)
}
func toJSON(s string) template.JS {
return template.JS(s)
}
func dictFunc(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, errors.New("invalid dict call")
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
return nil, errors.New("dict keys must be strings")
}
dict[key] = values[i+1]
}
return dict, nil
}
func tdefault(val interface{}, def interface{}) interface{} {
switch val.(type) {
case string:
if len(val.(string)) == 0 {
fmt.Println("empty string")
return def
}
case bool:
if !val.(bool) {
fmt.Println("false bool")
return def
}
case nil:
fmt.Println("nil type")
return def
}
fmt.Println("fallthru")
return val
}
func createFuncMap() template.FuncMap {
return template.FuncMap{
"html": toHTML,
"dict": dictFunc,
"default": tdefault,
"json": toJSON,
}
}