package http
import (
"fmt"
"html/template"
"net/http"
"path/filepath"
"time"
"superbanka/internal/platform"
)
type ViewData struct {
Title string
Page string
CSRFToken string
Flash string
Error string
User any
Admin any
Data any
}
type Renderer struct {
templates *template.Template
}
func NewRenderer() (*Renderer, error) {
funcs := template.FuncMap{
"money": platform.FormatCZK,
"dt": func(t time.Time) string {
if t.IsZero() {
return ""
}
return t.Format("02. 01. 2006 15:04")
},
}
templates, err := template.New("all").Funcs(funcs).ParseGlob(filepath.Join("web", "templates", "layouts", "*.gohtml"))
if err != nil {
return nil, fmt.Errorf("parse layout templates: %w", err)
}
templates, err = templates.ParseGlob(filepath.Join("web", "templates", "pages", "*.gohtml"))
if err != nil {
return nil, fmt.Errorf("parse page templates: %w", err)
}
return &Renderer{templates: templates}, nil
}
func (r *Renderer) HTML(w http.ResponseWriter, status int, data ViewData) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
if err := r.templates.ExecuteTemplate(w, "layouts/base", data); err != nil {
http.Error(w, fmt.Sprintf("render template: %v", err), http.StatusInternalServerError)
}
}