summaryrefslogtreecommitdiff
path: root/templ/template.go
blob: 8fed9651abf570805ce64164df043473564d621f (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
package templ

import (
	"embed"
	"html/template"
	"sync"
)

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

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

var baseTpl *template.Template

func init() {
	baseTpl = template.Must(template.ParseFS(fs, "base.tpl"))
}

func Lookup(name string) *template.Template {
	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
	}

	b := template.Must(baseTpl.Clone())
	t := template.Must(b.ParseFS(fs, name+".tpl"))
	templates[name] = t
	return t
}