From 65cce5b723a83b29cb48dcf6b1f9e312fcb588dc Mon Sep 17 00:00:00 2001 From: Jan Dittberner Date: Sat, 21 May 2022 20:57:32 +0200 Subject: [PATCH] Use embedded templates --- cmd/boardvoting/handlers.go | 41 +++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 22 deletions(-) diff --git a/cmd/boardvoting/handlers.go b/cmd/boardvoting/handlers.go index 5c19fc0..5530672 100644 --- a/cmd/boardvoting/handlers.go +++ b/cmd/boardvoting/handlers.go @@ -20,6 +20,7 @@ package main import ( "fmt" "html/template" + "io/fs" "net/http" "path/filepath" "strings" @@ -29,42 +30,38 @@ import ( "github.com/gorilla/csrf" "git.cacert.org/cacert-boardvoting/internal/models" + "git.cacert.org/cacert-boardvoting/ui" ) func newTemplateCache() (map[string]*template.Template, error) { 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 { return nil, fmt.Errorf("could not find page templates: %w", err) } + funcMaps := sprig.FuncMap() + funcMaps["nl2br"] = func(text string) template.HTML { + // #nosec G203 input is sanitized + return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "
")) + } + funcMaps["canManageUsers"] = func(*models.Voter) bool { + return false + } + funcMaps[csrf.TemplateTag] = csrf.TemplateField + 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", + ts, err := template.New("").Funcs(funcMaps).ParseFS( + ui.Files, + "html/base.html", + "html/partials/*.html", page, - } - - funcMaps := sprig.FuncMap() - funcMaps["nl2br"] = func(text string) template.HTML { - // #nosec G203 input is sanitized - return template.HTML(strings.ReplaceAll(template.HTMLEscapeString(text), "\n", "
")) - } - funcMaps["canManageUsers"] = func(*models.Voter) bool { - return false - } - funcMaps[csrf.TemplateTag] = csrf.TemplateField - - ts, err := template.New("").Funcs(funcMaps).ParseFiles(files...) + ) 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