diff options
-rw-r--r-- | templ/template.go | 27 |
1 files changed, 25 insertions, 2 deletions
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 } |