/
templates.go
125 lines (98 loc) · 2.38 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package web
import (
"html/template"
"github.com/yosssi/ace"
"net/http"
"github.com/jbrook/go-web-utils/i18n"
"log"
"strings"
"time"
"strconv"
"fmt"
)
const basePath = "templates"
const baseTemplateName = "layout"
type TemplateData map[string]interface{}
type TemplateConfig struct {
Asset func(name string) ([]byte, error)
Root string
}
var templateConfig TemplateConfig
func GetTemplate(name string, r *http.Request) *template.Template {
data := GetTemplateData(r)
funcMap := template.FuncMap{
// FIXME: Work out how the calling application can inject functions into the function map
"GetFirstLetter": func(s string) string {
if len(s) == 0 {
return s
}
bts := []byte(s)
frst := []byte{bts[0]}
return strings.ToUpper(string(frst))
},
"IsChecked": func(s string, v string) bool {
//if logger.IsDebug() {
// logger.Debug("IsChecked", "s", s, "v", v, "return", s == v)
//}
return s == v
},
"IsVoucherActive": func(a bool) string {
if a {
return "a-active-voucher"
} else {
return ""
}
},
"Now": func() time.Time {
return time.Now()
},
"noescape": func(s string) template.HTML {
return template.HTML(s)
},
"FormatMoney": func(f float64) string {
return strconv.FormatFloat(f, 'f', 2, 32)
},
"static": GetStaticPath,
"T": data["UnsafeT"],
}
tpl, err := ace.Load(baseTemplateName, name, &ace.Options{
Asset: templateConfig.Asset,
BaseDir: basePath,
FuncMap: funcMap,
})
if err != nil {
log.Fatalf("Could not load template %s: %s", name, err)
}
fmt.Printf("tpl: %v", tpl)
// Specify again here because tpl is cached
tpl.Funcs(funcMap)
if err != nil {
log.Fatalf("Could not load template %s: %s", name, err)
}
return tpl
}
func InitTemplates(config TemplateConfig) {
templateConfig = config
initStaticPath(config.Root)
}
func getDefaultTemplateData(r *http.Request) TemplateData {
data := make(TemplateData)
//data["csrf"] = getCsrfHTML(r)
data["request_uri"] = r.RequestURI
//data["root"] = templateConfig.Root
return data
}
func sanitizeData(data TemplateData) {
futureTs := make(map[string]i18n.FutureTranslation)
for key, value := range data {
switch t := value.(type) {
case string:
data[key] = template.HTML(template.HTMLEscapeString(t))
case i18n.FutureTranslation:
futureTs[key] = t
}
}
for key, value := range futureTs {
data[key] = value()
}
}