all repos — vite @ 81b8a3faf63f5b53e9d6e95aa09149941c4a2f11

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

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}
60
61func (t *Tmpl) Write(dest string, name string, data interface{}) error {
62	w, err := os.Create(dest)
63	if err != nil {
64		return err
65	}
66
67	return t.ExecuteTemplate(w, name, data)
68}