learn-go/snippetbox/cmd/web/templates.go

64 lines
1.1 KiB
Go
Raw Permalink Normal View History

2024-01-25 21:41:06 +00:00
package main
import (
2024-01-25 23:06:28 +00:00
"html/template"
2024-02-08 20:54:00 +00:00
"io/fs"
2024-01-25 23:06:28 +00:00
"path/filepath"
2024-01-25 23:43:07 +00:00
"time"
2024-01-25 23:06:28 +00:00
2024-01-25 21:41:06 +00:00
"snippetbox.chaosfem.tw/internal/models"
2024-02-08 20:54:00 +00:00
"snippetbox.chaosfem.tw/ui"
2024-01-25 21:41:06 +00:00
)
type templateData struct {
2024-02-08 06:46:35 +00:00
CurrentYear int
Snippet models.Snippet
Snippets []models.Snippet
Form any
Flash string
IsAuthenticated bool
2024-02-08 07:04:06 +00:00
CSRFToken string
2024-01-25 21:41:06 +00:00
}
2024-01-25 23:06:28 +00:00
2024-01-25 23:43:07 +00:00
// humanDate ...
func humanDate(t time.Time) string {
2024-02-13 19:59:38 +00:00
if t.IsZero() {
return ""
}
return t.UTC().Format("02 Jan 2006 at 15:04")
2024-01-25 23:43:07 +00:00
}
var functions = template.FuncMap{
"humanDate": humanDate,
}
2024-01-25 23:06:28 +00:00
// newTemplateCache ...
func newTemplateCache() (map[string]*template.Template, error) {
cache := map[string]*template.Template{}
2024-02-08 20:54:00 +00:00
pages, err := fs.Glob(ui.Files, "html/pages/*.tmpl")
2024-01-25 23:06:28 +00:00
if err != nil {
return nil, err
}
for _, page := range pages {
name := filepath.Base(page)
2024-02-08 20:54:00 +00:00
patterns := []string{
"html/base.tmpl",
"html/partials/*.tmpl",
page,
2024-01-25 23:06:28 +00:00
}
2024-02-08 20:54:00 +00:00
ts, err := template.New(name).Funcs(functions).ParseFS(ui.Files, patterns...)
2024-01-25 23:06:28 +00:00
if err != nil {
return nil, err
}
cache[name] = ts
}
return cache, nil
}