webweav.ing/cmd/web/templates.go

71 lines
1.5 KiB
Go
Raw Normal View History

2024-01-22 20:43:46 +00:00
package main
import (
2024-03-03 17:53:09 +00:00
"net/http"
2024-01-22 20:43:46 +00:00
"path/filepath"
"text/template"
2024-03-03 17:53:09 +00:00
"time"
2024-01-22 20:43:46 +00:00
)
type templateData struct {
2024-03-03 17:53:09 +00:00
CurrentYear int
Feeds []string
2024-03-03 21:05:19 +00:00
Title string
2024-03-03 21:51:19 +00:00
Errors map[string]string
2024-01-22 20:43:46 +00:00
}
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
}
2024-03-03 17:53:09 +00:00
// 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
}
2024-01-22 20:43:46 +00:00
return cache, nil
}
2024-03-03 17:53:09 +00:00
func newTemplateData(r *http.Request) *templateData {
return &templateData{
CurrentYear: time.Now().Year(),
}
}