morning-coffee/templates.go

49 lines
946 B
Go
Raw Normal View History

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: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
}
2024-09-21 17:09:43 +00:00
type RenderMeta struct {
RenderStart time.Time
}
type RenderContext struct {
Data interface{}
Meta RenderMeta
}
return tmpl.ExecuteTemplate(w, "base", RenderContext{Data: data, Meta: RenderMeta{RenderStart: start}})
2024-09-21 04:50:10 +00:00
}