summaryrefslogtreecommitdiff
path: root/templ/template.go
blob: 9def1b870a433e91214830ac0f679c82971e8693 (plain)
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package templ

import (
	"embed"
	"html/template"
	"io/fs"
	"os"
	"sync"

	"github.com/Necoro/form"
)

//go:embed *.tpl
var fsEmbed embed.FS

var templates = make(map[string]*template.Template)
var muTpl sync.RWMutex

var baseTpl *template.Template
var formBuilder form.Builder

var isLive = sync.OnceValue(checkLive)

func init() {
	loadBase(fsEmbed)
}

func checkLive() bool {
	return os.Getenv("GOSTEN_LIVE") != ""
}

func loadBase(fs fs.FS) {
	baseTpl = template.Must(template.New("base.tpl").
		Funcs(form.FuncMap()).
		ParseFS(fs, "base.tpl", "form.tpl"))
	formBuilder = form.Builder{InputTemplate: baseTpl.Lookup("formItem")}
	baseTpl.Funcs(formBuilder.FuncMap())
}

func Lookup(name string) *template.Template {
	if isLive() {
		fs := os.DirFS("templ/")
		loadBase(fs)
		return getTemplate(name, fs)
	}

	muTpl.RLock()
	tpl := templates[name]
	muTpl.RUnlock()

	if tpl == nil {
		return parse(name)
	}
	return tpl
}

func parse(name string) *template.Template {
	muTpl.Lock()
	defer muTpl.Unlock()

	if tpl := templates[name]; tpl != nil {
		// might've been created by another goroutine
		return tpl
	}

	t := getTemplate(name, fsEmbed)
	templates[name] = t
	return t
}

func getTemplate(name string, fs fs.FS) *template.Template {
	b := template.Must(baseTpl.Clone())
	t := template.Must(b.ParseFS(fs, name+".tpl"))
	return t
}