From 9846cf2211c1a2e4e8eea44e2fbf46b50876d39e Mon Sep 17 00:00:00 2001 From: Jan-Lukas Else Date: Sun, 20 Sep 2020 17:47:54 +0200 Subject: [PATCH] Rework template initialization, load all templates from template directory --- main.go | 6 +++++- render.go | 36 ++++++++++++++++++++++++++---------- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/main.go b/main.go index 7c36d8a..ae09045 100644 --- a/main.go +++ b/main.go @@ -25,7 +25,11 @@ func main() { return } initMarkdown() - initRendering() // Needs assets + err = initRendering() // Needs assets + if err != nil { + log.Fatal(err) + return + } // Prepare graceful shutdown quit := make(chan os.Signal, 1) diff --git a/render.go b/render.go index 0a8fa6c..7338906 100644 --- a/render.go +++ b/render.go @@ -2,26 +2,31 @@ package main import ( "bytes" - "fmt" "github.com/araddon/dateparse" "html/template" "log" "net/http" + "os" + "path" + "path/filepath" + "strings" "time" ) +const templatesDir = "templates" +const templatesExt = ".gohtml" + +const templateBase = "base" const templatePost = "post" const templateError = "error" const templateRedirect = "redirect" const templateIndex = "index" -const templateSummary = "summary" const templateTaxonomy = "taxonomy" -const templateMenu = "menu" var templates map[string]*template.Template var templateFunctions template.FuncMap -func initRendering() { +func initRendering() error { templateFunctions = template.FuncMap{ "blog": func() *configBlog { return appConfig.Blog @@ -69,13 +74,24 @@ func initRendering() { } templates = make(map[string]*template.Template) - for _, name := range []string{templatePost, templateError, templateRedirect, templateIndex, templateSummary, templateTaxonomy, templateMenu} { - templates[name] = loadTemplate(name) - } -} -func loadTemplate(name string) *template.Template { - return template.Must(template.New(name).Funcs(templateFunctions).ParseFiles("templates/base.gohtml", fmt.Sprintf("templates/%s.gohtml", name))) + baseTemplatePath := path.Join(templatesDir, templateBase+templatesExt) + err := filepath.Walk(templatesDir, func(p string, info os.FileInfo, err error) error { + if info.Mode().IsRegular() && path.Ext(p) == templatesExt { + name := strings.TrimSuffix(path.Base(p), templatesExt) + if name != templateBase { + templates[name], err = template.New(name).Funcs(templateFunctions).ParseFiles(baseTemplatePath, p) + if err != nil { + return err + } + } + } + return nil + }) + if err != nil { + return err + } + return nil } func render(w http.ResponseWriter, template string, data interface{}) {