From d24f48bc5258d0b012b33bf90e67d0c56aaa50ed Mon Sep 17 00:00:00 2001 From: Marc Cataford Date: Sat, 21 Sep 2024 00:50:10 -0400 Subject: [PATCH] refactor: extract template rendering --- routes.go | 10 +++------- templates.go | 27 +++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 7 deletions(-) create mode 100644 templates.go diff --git a/routes.go b/routes.go index a4a04d4..a04e7b8 100644 --- a/routes.go +++ b/routes.go @@ -5,7 +5,6 @@ import ( "fmt" "net/http" "net/url" - "text/template" ) type Link struct { @@ -26,8 +25,7 @@ func healthcheck(w http.ResponseWriter, r *http.Request) { // // Static content for the about page. func about(w http.ResponseWriter, r *http.Request) { - tmpl, _ := template.New("about").ParseFiles("templates/about.html.tmpl", "templates/base.html.tmpl") - tmpl.ExecuteTemplate(w, "base", nil) + Render(w, "about", nil) } // Feeds list @@ -41,8 +39,7 @@ func listContent(w http.ResponseWriter, r *http.Request) { links = append(links, formattedItems...) } - tmpl, _ := template.New("base").ParseFiles("templates/index.html.tmpl", "templates/base.html.tmpl") - tmpl.ExecuteTemplate(w, "base", links) + Render(w, "index", links) } // Manage content @@ -74,6 +71,5 @@ func manageContent(w http.ResponseWriter, r *http.Request) { Feeds map[string]string } - tmpl, _ := template.New("manage").ParseFiles("templates/manage.html.tmpl", "templates/base.html.tmpl") - tmpl.ExecuteTemplate(w, "base", ManageTmplData{Feeds: allFeeds}) + Render(w, "manage", ManageTmplData{Feeds: allFeeds}) } diff --git a/templates.go b/templates.go new file mode 100644 index 0000000..cd9d894 --- /dev/null +++ b/templates.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "io" + "path/filepath" + "text/template" +) + +func Render(w io.Writer, templateName string, data interface{}) error { + asTemplatePath := func(templateName string) string { + return filepath.Join("templates", fmt.Sprintf("%s.html.tmpl", templateName)) + } + + templatePartials := []string{ + asTemplatePath(templateName), + asTemplatePath("base"), + } + + tmpl, err := template.New(templateName).ParseFiles(templatePartials...) + + if err != nil { + return err + } + + return tmpl.ExecuteTemplate(w, "base", data) +}