-
Notifications
You must be signed in to change notification settings - Fork 1
/
templates.go
101 lines (97 loc) · 2.33 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
package server
import (
"errors"
"github.com/nrc-no/notcore/internal/locales"
"html/template"
"strings"
"time"
"github.com/nrc-no/notcore/web"
)
type templates map[string]*template.Template
func parseTemplates(
loginURL string,
refreshURL string,
tokenRefreshInterval time.Duration,
) (templates, error) {
t := make(templates)
entries, err := web.Content.ReadDir("templates")
if err != nil {
return nil, err
}
for _, entry := range entries {
if entry.IsDir() {
continue
}
if entry.Name() == "nav.gohtml" {
continue
}
name := entry.Name()
tpl := template.New("")
tpl.Funcs(map[string]any{
"add": func(a, b int) int {
return a + b
},
"sub": func(a, b int) int {
return a - b
},
"age": func(dateOfBirth time.Time) int {
return int(time.Since(dateOfBirth).Hours() / 24 / 365)
},
"joinStrings": func(a []string, b string) string {
return strings.Join(a, b)
},
"contains": func(arr []string, str string) bool {
for _, v := range arr {
if v == str {
return true
}
}
return false
},
"loginURL": func() string {
return loginURL
},
"tokenRefreshURL": func() string {
return refreshURL
},
"tokenRefreshInterval": func() time.Duration {
return tokenRefreshInterval
},
"time": func() TimeFunctions {
return TimeFunctions{}
},
"concat": func(strs ...string) string {
return strings.Join(strs, "")
},
"attr": func(val string) template.HTMLAttr {
return template.HTMLAttr(val)
},
"safe": func(val string) template.HTML {
return template.HTML(val)
},
"dict": func(values ...interface{}) (map[string]interface{}, error) {
if len(values)%2 != 0 {
return nil, errors.New("dict must have an even number of arguments")
}
dict := make(map[string]interface{})
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
},
"boolPointerToValue": func(i *bool) bool { return *i },
"translate": func(id string, args ...interface{}) string {
return locales.GetLocales().Translate(id, args...)
},
})
t[name], err = tpl.ParseFS(web.Content, "templates/**.gohtml", "templates/"+name)
if err != nil {
return nil, err
}
}
return t, nil
}