50 lines
925 B
Go
50 lines
925 B
Go
package static
|
|
|
|
import (
|
|
"bytes"
|
|
_ "embed"
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
type Context = map[string]any
|
|
|
|
var (
|
|
templates = make(map[string]*template.Template)
|
|
|
|
//go:embed templates/base.tmpl
|
|
baseTmpl string
|
|
Base = "base"
|
|
|
|
//go:embed templates/new.tmpl
|
|
newTmpl string
|
|
New = "new"
|
|
)
|
|
|
|
func init() {
|
|
templates[Base] = template.Must(template.New("").Funcs(funcMap).Parse(baseTmpl))
|
|
templates[New] = template.Must(template.New("").Funcs(funcMap).Parse(newTmpl))
|
|
}
|
|
|
|
func Tmpl(w io.Writer, name string, ctx any) error {
|
|
if tmpl, ok := templates[name]; ok {
|
|
return tmpl.Execute(w, ctx)
|
|
}
|
|
return fmt.Errorf("unknown template %q", name)
|
|
}
|
|
|
|
var funcMap = template.FuncMap{
|
|
"tmpl": func(name string, ctx any) template.HTML {
|
|
var buf bytes.Buffer
|
|
err := Tmpl(&buf, name, ctx)
|
|
if err != nil {
|
|
log.Err(err).Msg("")
|
|
return ""
|
|
}
|
|
return template.HTML(buf.String())
|
|
},
|
|
}
|