lishwist/server/templates/templates.go

64 lines
2.2 KiB
Go

package templates
import (
"fmt"
"log"
"net/http"
"text/template"
)
type InputProps struct {
Type string `json:",omitempty"`
Name string
Required bool `json:",omitempty"`
Value string
Error string `json:",omitempty"`
MinLength uint `json:",omitempty"`
}
func (p *InputProps) Validate() bool {
if p.Required && p.Value == "" {
p.Error = fmt.Sprintf("%v is required", p.Name)
return false
}
value_len := len(p.Value)
if p.MinLength > 0 && int(p.MinLength) > value_len {
p.Error = fmt.Sprintf("%v requires at least %v characters (currently %v characters)", p.Name, p.MinLength, value_len)
return false
}
return true
}
var tmpls map[string]*template.Template = loadTemplates()
func Execute(w http.ResponseWriter, name string, data any) {
err := tmpls[name].Execute(w, data)
if err != nil {
log.Printf("Failed to execute '%s' template: %s\n", name, err)
return
}
}
func loadTemplates() map[string]*template.Template {
homeTmpl := template.Must(template.ParseFiles("templates/base.gotmpl", "templates/home.gotmpl"))
loginTmpl := template.Must(template.ParseFiles("templates/base.gotmpl", "templates/login.gotmpl"))
registerTmpl := template.Must(template.ParseFiles("templates/base.gotmpl", "templates/register.gotmpl"))
foreignTmpl := template.Must(template.ParseFiles("templates/base.gotmpl", "templates/foreign_wishlist.gotmpl"))
publicWishlistTmpl := template.Must(template.ParseFiles("templates/base.gotmpl", "templates/public_foreign_wishlist.gotmpl"))
errorTmpl := template.Must(template.ParseFiles("templates/base.gotmpl", "templates/error_page.gotmpl"))
groupTmpl := template.Must(template.ParseFiles("templates/base.gotmpl", "templates/group_page.gotmpl"))
publicGroupTmpl := template.Must(template.ParseFiles("templates/base.gotmpl", "templates/public_group_page.gotmpl"))
return map[string]*template.Template{
"home.gotmpl": homeTmpl,
"login.gotmpl": loginTmpl,
"register.gotmpl": registerTmpl,
"foreign_wishlist.gotmpl": foreignTmpl,
"public_foreign_wishlist.gotmpl": publicWishlistTmpl,
"error_page.gotmpl": errorTmpl,
"group_page.gotmpl": groupTmpl,
"public_group_page.gotmpl": publicGroupTmpl,
}
}