tipus/pkg/template.go

42 lines
1.1 KiB
Go
Raw Normal View History

package pkg
import (
"fmt"
"html/template"
"io"
"net/http"
)
func templateFile(name string) string {
return "web/template/" + name
}
func mustRenderTemplate(wr io.Writer, r *http.Request, layout string, filename string, data interface{}) {
locale := getLocale(r)
user := getUser(r)
t := template.New(filename)
t.Funcs(template.FuncMap{
"gettext": locale.Get,
"pgettext": locale.GetC,
"currentLocale": func() string {
return locale.Language.String()
},
"csrfToken": func() template.HTML {
return template.HTML(fmt.Sprintf(`<input type="hidden" name="%s" value="%s">`, csrfTokenField, user.CsrfToken))
},
})
if _, err := t.ParseFiles(templateFile(filename), templateFile(layout), templateFile("form.gohtml")); err != nil {
panic(err)
}
if w, ok := wr.(http.ResponseWriter); ok {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
}
if err := t.ExecuteTemplate(wr, layout, data); err != nil {
panic(err)
}
}
func mustRenderWebTemplate(w io.Writer, r *http.Request, filename string, data interface{}) {
mustRenderTemplate(w, r, "web.gohtml", filename, data)
}