54 lines
1.4 KiB
Go
54 lines
1.4 KiB
Go
/*
|
|
* SPDX-FileCopyrightText: 2023 jordi fita mas <jfita@peritasoft.com>
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
*/
|
|
|
|
package template
|
|
|
|
import (
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
"net/http"
|
|
|
|
"dev.tandem.ws/tandem/camper/pkg/auth"
|
|
)
|
|
|
|
func templateFile(name string) string {
|
|
return "web/templates/" + name
|
|
}
|
|
|
|
func MustRender(w io.Writer, user *auth.User, filename string, data interface{}) {
|
|
layout := "layout.gohtml"
|
|
mustRenderLayout(w, user, layout, filename, data)
|
|
}
|
|
|
|
func mustRenderLayout(w io.Writer, user *auth.User, layout string, filename string, data interface{}) {
|
|
t := template.New(filename)
|
|
t.Funcs(template.FuncMap{
|
|
"gettext": user.Locale.Get,
|
|
"pgettext": user.Locale.GetC,
|
|
"currentLocale": func() string {
|
|
return user.Locale.Language.String()
|
|
},
|
|
"isLoggedIn": func() bool {
|
|
return user.LoggedIn
|
|
},
|
|
"CSRFHeader": func() string {
|
|
return fmt.Sprintf(`"%s": "%s"`, auth.CSRFTokenHeader, user.CSRFToken)
|
|
},
|
|
"CSRFInput": func() template.HTML {
|
|
return template.HTML(fmt.Sprintf(`<input type="hidden" name="%s" value="%s">`, auth.CSRFTokenField, user.CSRFToken))
|
|
},
|
|
})
|
|
if _, err := t.ParseFiles(templateFile(layout), templateFile(filename)); err != nil {
|
|
panic(err)
|
|
}
|
|
if rw, ok := w.(http.ResponseWriter); ok {
|
|
rw.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
}
|
|
if err := t.ExecuteTemplate(w, layout, data); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|