Ronbun/cmd/web/templates.go

65 lines
1.3 KiB
Go

package main
import (
"html/template"
"io/fs"
"path/filepath"
"time"
"github.com/Thomasorus/Ronbun-CMS/internal/models"
"github.com/Thomasorus/Ronbun-CMS/ui"
)
// Type for the returned template data
type templateData struct {
CurrentYear int
Page models.Page
Pages []models.Page
Form any
Flash string
BreadCrumb []models.BreadCrumbItem
IsAuthenticated bool
CSRFToken string
Files []File
Theme string
}
// Convert dates to human readable dates
func humanDate(t time.Time) string {
return t.Format("Mon, 02 Jan 2006 15:04:05 MST")
}
// Add custom functions to templates
var functions = template.FuncMap{
"humanDate": humanDate,
}
// Put all templates into a memory cache to avoid reading from disk
func newTemplateCache() (map[string]*template.Template, error) {
cache := map[string]*template.Template{}
// Retrieve paths for all page templates
pages, err := fs.Glob(ui.Files, "html/pages/*tmpl")
if err != nil {
return nil, err
}
for _, page := range pages {
name := filepath.Base(page)
patterns := []string{
"html/pages/base.tmpl",
"html/partials/*.tmpl",
page,
}
ts, err := template.New(name).Funcs(functions).ParseFS(ui.Files, patterns...)
if err != nil {
return nil, err
}
cache[name] = ts
}
return cache, nil
}