Use embedded templates

This commit is contained in:
Jan Dittberner 2022-05-21 20:57:32 +02:00
parent ff93acb65c
commit 65cce5b723

View file

@ -20,6 +20,7 @@ package main
import ( import (
"fmt" "fmt"
"html/template" "html/template"
"io/fs"
"net/http" "net/http"
"path/filepath" "path/filepath"
"strings" "strings"
@ -29,29 +30,17 @@ import (
"github.com/gorilla/csrf" "github.com/gorilla/csrf"
"git.cacert.org/cacert-boardvoting/internal/models" "git.cacert.org/cacert-boardvoting/internal/models"
"git.cacert.org/cacert-boardvoting/ui"
) )
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/*.html") pages, err := fs.Glob(ui.Files, "html/pages/*.html")
if err != nil { if err != nil {
return nil, fmt.Errorf("could not find page templates: %w", err) return nil, fmt.Errorf("could not find page templates: %w", err)
} }
for _, page := range pages {
name := filepath.Base(page)
files := []string{
"./ui/html/base.html",
"./ui/html/partials/motion_actions.html",
"./ui/html/partials/motion_display.html",
"./ui/html/partials/motion_status_class.html",
"./ui/html/partials/nav.html",
"./ui/html/partials/pagination.html",
page,
}
funcMaps := sprig.FuncMap() funcMaps := sprig.FuncMap()
funcMaps["nl2br"] = func(text string) template.HTML { funcMaps["nl2br"] = func(text string) template.HTML {
// #nosec G203 input is sanitized // #nosec G203 input is sanitized
@ -62,9 +51,17 @@ func newTemplateCache() (map[string]*template.Template, error) {
} }
funcMaps[csrf.TemplateTag] = csrf.TemplateField funcMaps[csrf.TemplateTag] = csrf.TemplateField
ts, err := template.New("").Funcs(funcMaps).ParseFiles(files...) for _, page := range pages {
name := filepath.Base(page)
ts, err := template.New("").Funcs(funcMaps).ParseFS(
ui.Files,
"html/base.html",
"html/partials/*.html",
page,
)
if err != nil { if err != nil {
return nil, fmt.Errorf("could not parse templates: %w", err) return nil, fmt.Errorf("could not parse base template: %w", err)
} }
cache[name] = ts cache[name] = ts