48 lines
946 B
Go
48 lines
946 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"path/filepath"
|
|
"text/template"
|
|
"time"
|
|
)
|
|
|
|
func getRenderDuration(start time.Time) time.Duration {
|
|
return time.Now().Sub(start)
|
|
}
|
|
|
|
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"),
|
|
asTemplatePath("footer"),
|
|
}
|
|
|
|
start := time.Now()
|
|
|
|
tmpl := template.New(templateName).Funcs(template.FuncMap{
|
|
"getRenderDuration": getRenderDuration,
|
|
})
|
|
|
|
tmpl, err := tmpl.ParseFiles(templatePartials...)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
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}})
|
|
}
|