include-templates.go (1126B)
1 package main 2 3 import ( 4 "fmt" 5 "html/template" 6 "net/url" 7 "strings" 8 ) 9 10 // InitTemplates loads and parses all HTML templates with helper functions 11 func InitTemplates() (*template.Template, error) { 12 return template.New("").Funcs(template.FuncMap{ 13 "add": func(a, b int) int { return a + b }, 14 "sub": func(a, b int) int { return a - b }, 15 "pathEscape": url.PathEscape, 16 "hasPrefix": func(s, prefix string) bool { 17 return strings.HasPrefix(s, prefix) 18 }, 19 "hasAnySuffix": func(s string, suffixes ...string) bool { 20 for _, suf := range suffixes { 21 if strings.HasSuffix(strings.ToLower(s), suf) { 22 return true 23 } 24 } 25 return false 26 }, 27 "dict": func(values ...interface{}) (map[string]interface{}, error) { 28 if len(values)%2 != 0 { 29 return nil, fmt.Errorf("dict requires an even number of args") 30 } 31 dict := make(map[string]interface{}, len(values)/2) 32 for i := 0; i < len(values); i += 2 { 33 key, ok := values[i].(string) 34 if !ok { 35 return nil, fmt.Errorf("dict keys must be strings") 36 } 37 dict[key] = values[i+1] 38 } 39 return dict, nil 40 }, 41 }).ParseGlob("templates/*.html") 42 }