From 3218627068f7866c1118f1acde1a05eb34293f5e Mon Sep 17 00:00:00 2001 From: Matt Baer Date: Tue, 30 Mar 2021 19:00:56 -0400 Subject: [PATCH] Add base template --- templates.go | 19 ++++++++++++++++--- templates/base.tmpl | 23 +++++++++++++++++++++++ templates/profile.tmpl | 1 + 3 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 templates/base.tmpl diff --git a/templates.go b/templates.go index 719d691..20c281d 100644 --- a/templates.go +++ b/templates.go @@ -4,23 +4,36 @@ import ( "html/template" "io" "log" + "net/http" ) -var profileTmpl *template.Template +var templates = map[string]*template.Template{} const templatesDir = "templates/" func init() { - profileTmpl = template.Must(template.New("profile").ParseFiles(templatesDir + "profile.tmpl")) + initTemplate("profile") +} + +func initTemplate(name string) { + templates[name] = template.Must(template.New(name).ParseFiles(templatesDir+name+".tmpl", templatesDir+"base.tmpl")) } // renderTemplate retrieves the given template and renders it to the given io.Writer. // If something goes wrong, the error is logged and returned. func renderTemplate(w io.Writer, tmpl string, data interface{}) error { - err := profileTmpl.ExecuteTemplate(w, tmpl, data) + err := templates[tmpl].ExecuteTemplate(w, tmpl, data) if err != nil { log.Printf("[ERROR] Error rendering %s: %s\n", tmpl, err) } return err } + +func (app *app) pageHandler(name string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + handleError(w, r, func() error { + return renderTemplate(w, name, nil) + }()) + } +} diff --git a/templates/base.tmpl b/templates/base.tmpl new file mode 100644 index 0000000..3900f92 --- /dev/null +++ b/templates/base.tmpl @@ -0,0 +1,23 @@ +{{define "pre-end-body"}} + +{{end}} + +{{define "footer"}} + +{{end}} diff --git a/templates/profile.tmpl b/templates/profile.tmpl index e9a5bfa..10dcfd1 100644 --- a/templates/profile.tmpl +++ b/templates/profile.tmpl @@ -30,6 +30,7 @@ + {{template "pre-end-body" .}} {{end}}