webweav.ing/cmd/web/templates.go

71 lines
1.5 KiB
Go

package main
import (
"net/http"
"path/filepath"
"text/template"
"time"
)
type templateData struct {
CurrentYear int
Feeds []string
Title string
Errors map[string]string
}
func newTemplateCache() (map[string]*template.Template, error) {
cache := map[string]*template.Template{}
pages, err := filepath.Glob("./ui/html/pages/*.tmpl.html")
if err != nil {
return nil, err
}
for _, page := range pages {
name := filepath.Base(page)
ts, err := template.ParseFiles("./ui/html/base.tmpl.html")
if err != nil {
return nil, err
}
// parse all partials into the template set
ts, err = ts.ParseGlob("./ui/html/partials/*.tmpl.html")
if err != nil {
return nil, err
}
// parse the page template last
ts, err = ts.ParseFiles(page)
if err != nil {
return nil, err
}
cache[name] = ts
}
// htmx elements should just be raw html, so we parse those separately
hxElems, err := filepath.Glob("./ui/html/htmx/*.tmpl.html")
if err != nil {
return nil, err
}
for _, hxElem := range hxElems {
name := filepath.Base(hxElem)
ts, err := template.ParseFiles(hxElem)
if err != nil {
return nil, err
}
cache[name] = ts
}
return cache, nil
}
func newTemplateData(r *http.Request) *templateData {
return &templateData{
CurrentYear: time.Now().Year(),
}
}