-
Notifications
You must be signed in to change notification settings - Fork 1
/
template_engine.go
49 lines (40 loc) · 1.09 KB
/
template_engine.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
package infrastructure
import (
"fmt"
"html/template"
"io/fs"
"net/http"
"strings"
"github.com/gofiber/template/html"
"golang.org/x/text/message"
)
func TemplateEngine(viewsFS fs.FS, printers map[string]*message.Printer) (*html.Engine, error) {
engine := html.NewFileSystem(http.FS(viewsFS), ".html")
engine.AddFunc("t", func(lang, key string, values ...interface{}) template.HTML {
return template.HTML(printers[lang].Sprintf(key, values...))
})
engine.AddFunc("dict", func(values ...interface{}) map[string]interface{} {
if len(values)%2 != 0 {
fmt.Println("invalid dict call")
return nil
}
dict := make(map[string]interface{}, len(values)/2)
for i := 0; i < len(values); i += 2 {
key, ok := values[i].(string)
if !ok {
fmt.Println("dict keys must be strings")
return nil
}
dict[key] = values[i+1]
}
return dict
})
engine.AddFunc("uppercase", func(text string) string {
return strings.ToUpper(text)
})
engine.AddFunc("notLast", notLast[string])
return engine, nil
}
func notLast[V any](slice []V, index int) bool {
return index < len(slice)-1
}