From d90b6db3e20ace806e66a761023296410f2cfed5 Mon Sep 17 00:00:00 2001 From: Trevor Sawler Date: Mon, 8 Feb 2021 19:24:28 -0400 Subject: [PATCH] Template cache part two --- pkg/render/render.go | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/pkg/render/render.go b/pkg/render/render.go index e024a71..90425b4 100644 --- a/pkg/render/render.go +++ b/pkg/render/render.go @@ -1,8 +1,10 @@ package render import ( + "bytes" "fmt" "html/template" + "log" "net/http" "path/filepath" ) @@ -11,20 +13,29 @@ var functions = template.FuncMap{} // RenderTemplate renders a template func RenderTemplate(w http.ResponseWriter, tmpl string) { - _, err := RenderTemplateTest(w) + tc, err := CreateTemplateCache() if err != nil { - fmt.Println("Error getting template cache", err) + log.Fatal(err) } - parsedTemplate, _ := template.ParseFiles("./templates/" + tmpl) + t, ok := tc[tmpl] + if !ok { + log.Fatal(err) + } + + buf := new(bytes.Buffer) - err = parsedTemplate.Execute(w, nil) + _ = t.Execute(buf, nil) + + _, err = buf.WriteTo(w) if err != nil { - fmt.Println("error parsing template:", err) + fmt.Println("error writing template to browser", err) } + } -func RenderTemplateTest(w http.ResponseWriter) (map[string]*template.Template, error) { +// CreateTemplateCache creates a template cache as a map +func CreateTemplateCache() (map[string]*template.Template, error) { myCache := map[string]*template.Template{} @@ -35,7 +46,6 @@ func RenderTemplateTest(w http.ResponseWriter) (map[string]*template.Template, e for _, page := range pages { name := filepath.Base(page) - fmt.Println("Page is currently", page) ts, err := template.New(name).Funcs(functions).ParseFiles(page) if err != nil { return myCache, err