apps/easel/render.go 1.3 K raw
1
package main
2
3
import (
4
	"bytes"
5
	"fmt"
6
	"html/template"
7
	"io/fs"
8
	"net/http"
9
	"path"
10
	"strings"
11
)
12
13
func buildTemplates() (map[string]*template.Template, error) {
14
	pages, err := fs.Glob(appFS, "templates/*.html")
15
	if err != nil {
16
		return nil, err
17
	}
18
19
	out := make(map[string]*template.Template, len(pages))
20
	for _, page := range pages {
21
		if strings.HasSuffix(page, "/base.html") {
22
			continue
23
		}
24
		tmpl, err := template.ParseFS(appFS, "templates/base.html", page)
25
		if err != nil {
26
			return nil, fmt.Errorf("parse %s: %w", page, err)
27
		}
28
		out[path.Base(page)] = tmpl
29
	}
30
	return out, nil
31
}
32
33
func (a *App) renderPage(w http.ResponseWriter, name string, data any) {
34
	a.renderPageStatus(w, http.StatusOK, name, data)
35
}
36
37
func (a *App) renderPageStatus(w http.ResponseWriter, status int, name string, data any) {
38
	tmpl, ok := a.Templates[name]
39
	if !ok {
40
		a.Log.Error("template missing", "name", name)
41
		http.Error(w, "template missing", http.StatusInternalServerError)
42
		return
43
	}
44
45
	var buf bytes.Buffer
46
	if err := tmpl.ExecuteTemplate(&buf, name, data); err != nil {
47
		a.Log.Error("template render failed", "name", name, "err", err)
48
		http.Error(w, "template error", http.StatusInternalServerError)
49
		return
50
	}
51
52
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
53
	w.WriteHeader(status)
54
	_, _ = w.Write(buf.Bytes())
55
}