From 91d14e414fc9c451879e834d7866ad765084a836 Mon Sep 17 00:00:00 2001 From: René Neumann Date: Sat, 10 Feb 2024 23:24:37 +0100 Subject: Add templating --- templ/base.tpl | 16 ++++++++++++++++ templ/index.tpl | 3 +++ templ/template.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 templ/base.tpl create mode 100644 templ/index.tpl create mode 100644 templ/template.go (limited to 'templ') diff --git a/templ/base.tpl b/templ/base.tpl new file mode 100644 index 0000000..e88d735 --- /dev/null +++ b/templ/base.tpl @@ -0,0 +1,16 @@ + + + + + {{block "title" .}}Kosten{{end}} + + + +{{block "body" .}} + Dummy Text +{{end}} +{{block "js" .}} + +{{end}} + + \ No newline at end of file diff --git a/templ/index.tpl b/templ/index.tpl new file mode 100644 index 0000000..2c52810 --- /dev/null +++ b/templ/index.tpl @@ -0,0 +1,3 @@ +{{define "body"}} + Das ist die Basis +{{end}} \ No newline at end of file diff --git a/templ/template.go b/templ/template.go new file mode 100644 index 0000000..8fed965 --- /dev/null +++ b/templ/template.go @@ -0,0 +1,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 +} -- cgit v1.2.3-54-g00ecf