sprechstunden-go/controllers/templates.go

48 lines
1.4 KiB
Go

package controllers
import (
"fmt"
"html/template"
"net/http"
"officeHours/models"
"os"
)
var funcs = template.FuncMap{
"DayName": models.DayName,
"divide": func(i int, j int) int { return i / j },
}
var baseTemplate = template.Must(template.ParseFiles("templates/base.html")).New("base.html").Funcs(funcs)
func (b *BaseHandler) serveTemplate(w http.ResponseWriter, name string, data any) {
full_name := "templates/" + name + ".html"
// check that template exists
info, err := os.Stat(full_name)
if (err != nil && os.IsNotExist(err)) || info.IsDir() {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404: Template nicht gefunden."))
return
}
tmpl, err := baseTemplate.ParseFiles(full_name)
if err != nil {
// TODO: log.Printf
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("500: Template "+full_name+" konnte nicht geparst werden : %s", err.Error())))
return
}
// TODO: cache templates in parsed state, but not executed
err = template.Must(tmpl.Clone()).Execute(w, data)
if err != nil {
// TODO: log.Printf
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("500: Template "+full_name+" konnte nicht ausgeführt werden : %s", err.Error())))
return
}
}
var RawTemplates = template.Must(template.New("").Funcs(funcs).ParseFiles(
"templates/confirmationMail",
"templates/td.html",
"templates/officeHourTable.html"))