From 569a2dac6617e9aef98ac99989515d53de698b98 Mon Sep 17 00:00:00 2001 From: René 'Necoro' Neumann Date: Thu, 15 Feb 2024 14:59:25 +0100 Subject: Add "live mode" that refreshes templates --- templ/template.go | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) (limited to 'templ') diff --git a/templ/template.go b/templ/template.go index d68c752..9def1b8 100644 --- a/templ/template.go +++ b/templ/template.go @@ -3,13 +3,15 @@ package templ import ( "embed" "html/template" + "io/fs" + "os" "sync" "github.com/Necoro/form" ) //go:embed *.tpl -var fs embed.FS +var fsEmbed embed.FS var templates = make(map[string]*template.Template) var muTpl sync.RWMutex @@ -17,7 +19,17 @@ 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")) @@ -26,6 +38,12 @@ func init() { } 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() @@ -45,8 +63,13 @@ func parse(name string) *template.Template { 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")) - templates[name] = t return t } -- cgit v1.2.3-54-g00ecf