gistea/static/templates.go

57 lines
1.1 KiB
Go

package static
import (
"bytes"
_ "embed"
"fmt"
"html/template"
"io"
"github.com/rs/zerolog/log"
)
type Context map[string]any
type Page string
var (
templates = make(map[Page]*template.Template)
//go:embed templates/base.tmpl
baseTmpl string
Base Page = "base"
//go:embed templates/new.tmpl
newTmpl string
New Page = "new"
//go:embed templates/landing.tmpl
landingTmpl string
Landing Page = "landing"
)
func init() {
templates[Base] = template.Must(template.New("").Funcs(funcMap).Parse(baseTmpl))
templates[New] = template.Must(template.New("").Funcs(funcMap).Parse(newTmpl))
templates[Landing] = template.Must(template.New("").Funcs(funcMap).Parse(landingTmpl))
}
func Tmpl(w io.Writer, name Page, ctx Context) 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 Page, ctx Context) template.HTML {
var buf bytes.Buffer
err := Tmpl(&buf, name, ctx)
if err != nil {
log.Err(err).Msg("")
return ""
}
return template.HTML(buf.String())
},
}