61 lines
1.8 KiB
Go
61 lines
1.8 KiB
Go
package controllers
|
|
|
|
import (
|
|
"fmt"
|
|
"html/template"
|
|
"log"
|
|
"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)
|
|
|
|
// 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(errMsg))
|
|
return
|
|
}
|
|
|
|
tmpl, err := baseTemplate.ParseFiles(full_name)
|
|
if err != nil {
|
|
errMsg := fmt.Sprintf("Template %s konnte nicht geparst werden : %s", full_name, err.Error())
|
|
log.Println(errMsg)
|
|
w.WriteHeader(http.StatusInternalServerError)
|
|
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 {
|
|
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(errMsg))
|
|
return
|
|
}
|
|
}
|
|
|
|
// standalone templates that should not be wrapped into the base.html
|
|
var RawTemplates, TemplateError = template.New("").Funcs(funcs).ParseFiles(
|
|
"templates/confirmationMail",
|
|
"templates/td.html",
|
|
"templates/officeHourTable.html")
|