morning-coffee/render_templates.go

59 lines
1.3 KiB
Go
Raw Normal View History

2024-09-21 17:16:15 +00:00
// Template rendering
//
// Abstracts the rendering of static HTML templates.
// Render(...) handles rendering the provided template with the
// default partial templates (header, footer, general base...), handles
// getting the paths to those template files and feeding the data (including
// some internally-generated context) when hydrating the template.
2024-09-21 04:50:10 +00:00
package main
import (
"fmt"
"io"
"path/filepath"
"text/template"
2024-09-21 17:09:43 +00:00
"time"
2024-09-21 04:50:10 +00:00
)
2024-09-21 17:16:15 +00:00
type RenderMeta struct {
RenderStart time.Time
Location string
2024-09-21 17:16:15 +00:00
}
type RenderContext struct {
Data interface{}
Meta RenderMeta
}
2024-09-21 17:09:43 +00:00
func getRenderDuration(start time.Time) time.Duration {
return time.Now().Sub(start)
}
2024-09-21 04:50:10 +00:00
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"),
2024-09-21 17:09:43 +00:00
asTemplatePath("footer"),
2024-09-21 04:50:10 +00:00
}
2024-09-21 17:09:43 +00:00
start := time.Now()
tmpl := template.New(templateName).Funcs(template.FuncMap{
"getRenderDuration": getRenderDuration,
})
tmpl, err := tmpl.ParseFiles(templatePartials...)
2024-09-21 04:50:10 +00:00
if err != nil {
return err
}
renderContext := RenderContext{Data: data, Meta: RenderMeta{RenderStart: start, Location: "America/New_York"}}
2024-09-21 17:09:43 +00:00
2024-09-21 17:16:15 +00:00
return tmpl.ExecuteTemplate(w, "base", renderContext)
2024-09-21 04:50:10 +00:00
}