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

60 lines
1.0 KiB
Go
Raw Normal View History

2024-01-25 21:41:06 +00:00
package main
import (
2024-01-25 23:06:28 +00:00
"html/template"
"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"
)
type templateData struct {
2024-01-25 23:43:07 +00:00
CurrentYear int
2024-01-30 23:51:20 +00:00
Snippet models.Snippet
Snippets []models.Snippet
Form any
2024-02-07 05:37:06 +00:00
Flash 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 {
return t.Format("02 Jan 2006 at 15:04")
}
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{}
pages, err := filepath.Glob("./ui/html/pages/*.tmpl")
if err != nil {
return nil, err
}
for _, page := range pages {
name := filepath.Base(page)
2024-01-25 23:43:07 +00:00
ts, err := template.New(name).Funcs(functions).ParseFiles("./ui/html/base.tmpl")
2024-01-25 23:06:28 +00:00
if err != nil {
return nil, err
}
ts, err = ts.ParseGlob("./ui/html/partials/*.tmpl")
if err != nil {
return nil, err
}
ts, err = ts.ParseFiles(page)
if err != nil {
return nil, err
}
cache[name] = ts
}
return cache, nil
}