all repos — vite @ 678fa38599dd50bf47e04e6440675b8e133b543c

a fast (this time, actually) and minimal static site generator

markdown/template/template.go (view raw)

 1package template
 2
 3import (
 4	"os"
 5	"path/filepath"
 6	"strings"
 7	"text/template"
 8)
 9
10type Tmpl struct {
11	*template.Template
12}
13
14func NewTmpl() *Tmpl {
15	tmpl := Tmpl{}
16	tmpl.Template = template.New("")
17	return &tmpl
18}
19
20func (t *Tmpl) SetFuncs(funcMap template.FuncMap) {
21	t.Template = t.Template.Funcs(funcMap)
22}
23
24func (t *Tmpl) Load(dir string) (err error) {
25	if dir, err = filepath.Abs(dir); err != nil {
26		return err
27	}
28
29	root := t.Template
30
31	if err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) (_ error) {
32		if err != nil {
33			return err
34		}
35
36		if filepath.Ext(path) != ".html" {
37			return
38		}
39
40		var rel string
41		if rel, err = filepath.Rel(dir, path); err != nil {
42			return err
43		}
44
45		rel = strings.Join(strings.Split(rel, string(os.PathSeparator)), "/")
46		newTmpl := root.New(rel)
47
48		var b []byte
49		if b, err = os.ReadFile(path); err != nil {
50			return err
51		}
52
53		_, err = newTmpl.Parse(string(b))
54		return err
55	}); err != nil {
56		return err
57	}
58	return nil
59}