learn-go/snippetbox/cmd/web/templates.go
2024-02-13 11:59:59 -08:00

64 lines
1.1 KiB
Go

package main
import (
"html/template"
"io/fs"
"path/filepath"
"time"
"snippetbox.chaosfem.tw/internal/models"
"snippetbox.chaosfem.tw/ui"
)
type templateData struct {
CurrentYear int
Snippet models.Snippet
Snippets []models.Snippet
Form any
Flash string
IsAuthenticated bool
CSRFToken string
}
// humanDate ...
func humanDate(t time.Time) string {
if t.IsZero() {
return ""
}
return t.UTC().Format("02 Jan 2006 at 15:04")
}
var functions = template.FuncMap{
"humanDate": humanDate,
}
// newTemplateCache ...
func newTemplateCache() (map[string]*template.Template, error) {
cache := map[string]*template.Template{}
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/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
}