| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "html/template" |
| 6 | "io/fs" |
| 7 | "net/http" |
| 8 | "path" |
| 9 | "strings" |
| 10 | |
| 11 | "github.com/stevedylandev/andromeda/pkg/web" |
| 12 | ) |
| 13 | |
| 14 | func buildTemplates() (map[string]*template.Template, error) { |
| 15 | pages, err := fs.Glob(appFS, "templates/*.html") |
| 16 | if err != nil { |
| 17 | return nil, err |
| 18 | } |
| 19 | |
| 20 | out := make(map[string]*template.Template, len(pages)) |
| 21 | for _, page := range pages { |
| 22 | if strings.HasSuffix(page, "/base.html") { |
| 23 | continue |
| 24 | } |
| 25 | tmpl, err := template.ParseFS(appFS, "templates/base.html", page) |
| 26 | if err != nil { |
| 27 | return nil, fmt.Errorf("parse %s: %w", page, err) |
| 28 | } |
| 29 | out[path.Base(page)] = tmpl |
| 30 | } |
| 31 | return out, nil |
| 32 | } |
| 33 | |
| 34 | func (a *App) renderPage(w http.ResponseWriter, name string, data any) { |
| 35 | tmpl, ok := a.Templates[name] |
| 36 | if !ok { |
| 37 | a.Log.Error("template missing", "name", name) |
| 38 | http.Error(w, "template missing", http.StatusInternalServerError) |
| 39 | return |
| 40 | } |
| 41 | web.Render(tmpl, w, name, data, a.Log) |
| 42 | } |