this repo has no description
1package tmpl
2
3import (
4 "html/template"
5 "log"
6 "os"
7 "path/filepath"
8 "strings"
9)
10
11func Load(tpath string) (*template.Template, error) {
12 tmpl := template.New("")
13 loadedTemplates := make(map[string]bool)
14
15 err := filepath.Walk(tpath, func(path string, info os.FileInfo, err error) error {
16 if err != nil {
17 return err
18 }
19
20 if !info.IsDir() && strings.HasSuffix(path, ".html") {
21 content, err := os.ReadFile(path)
22 if err != nil {
23 return err
24 }
25
26 relPath, err := filepath.Rel(tpath, path)
27 if err != nil {
28 return err
29 }
30
31 name := strings.TrimSuffix(relPath, ".html")
32 name = strings.ReplaceAll(name, string(filepath.Separator), "/")
33
34 _, err = tmpl.New(name).Parse(string(content))
35 if err != nil {
36 log.Printf("error parsing template %s: %v", name, err)
37 return err
38 }
39
40 loadedTemplates[name] = true
41 log.Printf("loaded template: %s", name)
42 return err
43 }
44 return nil
45 })
46
47 if err != nil {
48 return nil, err
49 }
50
51 log.Printf("total templates loaded: %d", len(loadedTemplates))
52 return tmpl, nil
53
54}