preparations for styling: refactor template rendering #1

Merged
Gonne merged 7 commits from styling into main 2022-09-26 10:46:05 +00:00
Showing only changes of commit a755a0b3e9 - Show all commits

View file

@ -3,6 +3,7 @@ package controllers
import (
"fmt"
"html/template"
"log"
"net/http"
"officeHours/models"
"os"
@ -14,33 +15,45 @@ var funcs = template.FuncMap{
}
var baseTemplate = template.Must(template.ParseFiles("templates/base.html")).New("base.html").Funcs(funcs)
// Execute a rendered full HTML page.
//
// If you just want to fill a template snippet, use the RawTemplates object.
//
// Parameters:
// - name is the name of the template file inside templates/, without .html suffix.
// - data is passed through to the template
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() {
errMsg := fmt.Sprintf("Template %s nicht gefunden", full_name)
log.Println(errMsg)
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404: Template nicht gefunden."))
w.Write([]byte(errMsg))
return
}
tmpl, err := baseTemplate.ParseFiles(full_name)
if err != nil {
// TODO: log.Printf
errMsg := fmt.Sprintf("Template %s konnte nicht geparst werden : %s", full_name, err.Error())
log.Println(errMsg)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("500: Template "+full_name+" konnte nicht geparst werden : %s", err.Error())))
w.Write([]byte(errMsg))
return
}
// TODO: cache templates in parsed state, but not executed
err = template.Must(tmpl.Clone()).Execute(w, data)
if err != nil {
// TODO: log.Printf
errMsg := fmt.Sprintf("Template %s konnte nicht ausgeführt werden : %s", full_name, err.Error())
log.Println(errMsg)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf("500: Template "+full_name+" konnte nicht ausgeführt werden : %s", err.Error())))
w.Write([]byte(errMsg))
return
}
}
// standalone templates that should not be wrapped into the base.html
var RawTemplates = template.Must(template.New("").Funcs(funcs).ParseFiles(
"templates/confirmationMail",
"templates/td.html",