lets-go:13.2 embed templates

This commit is contained in:
tamsin johnson 2024-02-08 12:54:00 -08:00
parent ba4f38b425
commit f5c642ba4e
2 changed files with 9 additions and 11 deletions

View File

@ -2,10 +2,12 @@ package main
import ( import (
"html/template" "html/template"
"io/fs"
"path/filepath" "path/filepath"
"time" "time"
"snippetbox.chaosfem.tw/internal/models" "snippetbox.chaosfem.tw/internal/models"
"snippetbox.chaosfem.tw/ui"
) )
type templateData struct { type templateData struct {
@ -31,7 +33,7 @@ var functions = template.FuncMap{
func newTemplateCache() (map[string]*template.Template, error) { func newTemplateCache() (map[string]*template.Template, error) {
cache := map[string]*template.Template{} cache := map[string]*template.Template{}
pages, err := filepath.Glob("./ui/html/pages/*.tmpl") pages, err := fs.Glob(ui.Files, "html/pages/*.tmpl")
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -39,17 +41,13 @@ func newTemplateCache() (map[string]*template.Template, error) {
for _, page := range pages { for _, page := range pages {
name := filepath.Base(page) name := filepath.Base(page)
ts, err := template.New(name).Funcs(functions).ParseFiles("./ui/html/base.tmpl") patterns := []string{
if err != nil { "html/base.tmpl",
return nil, err "html/partials/*.tmpl",
page,
} }
ts, err = ts.ParseGlob("./ui/html/partials/*.tmpl") ts, err := template.New(name).Funcs(functions).ParseFS(ui.Files, patterns...)
if err != nil {
return nil, err
}
ts, err = ts.ParseFiles(page)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -4,5 +4,5 @@ import (
"embed" "embed"
) )
//go:embed "static" //go:embed "html" "static"
var Files embed.FS var Files embed.FS