You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
48 lines
1.2 KiB
Go
48 lines
1.2 KiB
Go
3 years ago
|
package main
|
||
4 years ago
|
|
||
|
import (
|
||
|
"io"
|
||
|
"text/template"
|
||
|
|
||
3 years ago
|
"github.com/phc-dm/server-poisson/config"
|
||
3 years ago
|
"github.com/phc-dm/server-poisson/util"
|
||
4 years ago
|
)
|
||
|
|
||
|
// TemplateRenderer holds cached templates for rendering
|
||
|
type TemplateRenderer struct {
|
||
4 years ago
|
baseFile string
|
||
4 years ago
|
baseTemplate *template.Template
|
||
|
templateMap map[string]*template.Template
|
||
|
}
|
||
|
|
||
|
// NewTemplateRenderer constructs a template renderer with a base file
|
||
|
func NewTemplateRenderer(baseFile string) *TemplateRenderer {
|
||
|
return &TemplateRenderer{
|
||
4 years ago
|
baseFile: baseFile,
|
||
4 years ago
|
baseTemplate: template.Must(template.ParseFiles("./views/" + baseFile)),
|
||
|
templateMap: make(map[string]*template.Template),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
// Render the template
|
||
3 years ago
|
func (t *TemplateRenderer) Render(w io.Writer, name string, data util.H) error {
|
||
4 years ago
|
tmpl := t.templateMap[name]
|
||
3 years ago
|
|
||
3 years ago
|
if config.Mode == "development" || tmpl == nil {
|
||
|
if config.Mode == "development" {
|
||
4 years ago
|
tmpl = template.Must(template.ParseFiles("./views/" + t.baseFile))
|
||
|
} else {
|
||
|
tmpl = template.Must(t.baseTemplate.Clone())
|
||
|
}
|
||
|
|
||
4 years ago
|
tmpl.ParseFiles("./views/" + name)
|
||
|
t.templateMap[name] = tmpl
|
||
|
}
|
||
|
|
||
3 years ago
|
newData := util.H{}
|
||
|
newData.Apply(data)
|
||
|
newData["Config"] = config.Object()
|
||
|
|
||
|
return tmpl.ExecuteTemplate(w, "base", newData)
|
||
4 years ago
|
}
|