apps/posts/views.go 4.6 K raw
1
package main
2
3
//go:generate go run github.com/a-h/templ/cmd/templ@v0.3.1001 generate
4
5
import (
6
	"bytes"
7
	"html/template"
8
	"net/http"
9
	"sync"
10
11
	"github.com/a-h/templ"
12
)
13
14
// View models for the public pages. They are passed both to the templ
15
// components and to custom body templates, so their fields (including the
16
// promoted siteContext ones) are the contract documented on /admin/templates.
17
18
type indexView struct {
19
	siteContext
20
	BlogDescription string
21
	IntroHTML       template.HTML
22
	Posts           []Post
23
}
24
25
type postView struct {
26
	siteContext
27
	Post            Post
28
	RenderedContent template.HTML
29
	Weather         Weather
30
}
31
32
type pageView struct {
33
	siteContext
34
	Page            Page
35
	RenderedContent template.HTML
36
}
37
38
type postsView struct {
39
	siteContext
40
	Posts []Post
41
}
42
43
// templateKinds are the public views whose body can be replaced from
44
// /admin/templates. Each is stored in the "template_<kind>" setting.
45
var templateKinds = []struct{ Kind, Label string }{
46
	{"index", "home"},
47
	{"post", "post"},
48
	{"page", "page"},
49
	{"posts", "posts list"},
50
}
51
52
func isTemplateKind(kind string) bool {
53
	for _, k := range templateKinds {
54
		if k.Kind == kind {
55
			return true
56
		}
57
	}
58
	return false
59
}
60
61
func templateSettingKey(kind string) string { return "template_" + kind }
62
63
// overrides caches parsed custom body templates by kind.
64
type overrides struct {
65
	mu    sync.RWMutex
66
	tmpls map[string]*template.Template
67
}
68
69
func (o *overrides) get(kind string) *template.Template {
70
	o.mu.RLock()
71
	defer o.mu.RUnlock()
72
	return o.tmpls[kind]
73
}
74
75
func (o *overrides) set(kind string, t *template.Template) {
76
	o.mu.Lock()
77
	defer o.mu.Unlock()
78
	if o.tmpls == nil {
79
		o.tmpls = map[string]*template.Template{}
80
	}
81
	if t == nil {
82
		delete(o.tmpls, kind)
83
		return
84
	}
85
	o.tmpls[kind] = t
86
}
87
88
func (a *App) loadOverrides() {
89
	for _, k := range templateKinds {
90
		src, _ := getSetting(a.DB, templateSettingKey(k.Kind))
91
		if src == "" {
92
			continue
93
		}
94
		t, err := template.New(k.Kind).Parse(src)
95
		if err != nil {
96
			a.Log.Error("custom template parse failed", "kind", k.Kind, "err", err)
97
			continue
98
		}
99
		a.Overrides.set(k.Kind, t)
100
	}
101
}
102
103
// validateOverride parses src and executes it against sample data, so errors
104
// like unknown fields surface on save rather than on the live site.
105
func validateOverride(kind, src string) (*template.Template, error) {
106
	t, err := template.New(kind).Parse(src)
107
	if err != nil {
108
		return nil, err
109
	}
110
	var buf bytes.Buffer
111
	if err := t.Execute(&buf, sampleView(kind)); err != nil {
112
		return nil, err
113
	}
114
	return t, nil
115
}
116
117
// body returns the custom body for kind if one is set and renders cleanly,
118
// otherwise the default templ component.
119
func (a *App) body(kind string, data any, def templ.Component) templ.Component {
120
	t := a.Overrides.get(kind)
121
	if t == nil {
122
		return def
123
	}
124
	var buf bytes.Buffer
125
	if err := t.Execute(&buf, data); err != nil {
126
		a.Log.Error("custom template render failed, using default", "kind", kind, "err", err)
127
		return def
128
	}
129
	return templ.Raw(buf.String())
130
}
131
132
func (a *App) renderPublic(w http.ResponseWriter, r *http.Request, site siteContext, title string, meta, body templ.Component) {
133
	var buf bytes.Buffer
134
	if err := layout(site, title, meta, body).Render(r.Context(), &buf); err != nil {
135
		a.Log.Error("render failed", "err", err)
136
		http.Error(w, "render error", http.StatusInternalServerError)
137
		return
138
	}
139
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
140
	_, _ = buf.WriteTo(w)
141
}
142
143
// sampleView returns representative data for kind, used to validate custom
144
// templates and to check the starters match the templ defaults.
145
func sampleView(kind string) any {
146
	s := func(v string) *string { return &v }
147
	site := siteContext{
148
		BlogTitle: "My Blog",
149
		NavLinks:  []NavLink{{Label: "about", URL: "/about"}},
150
		SiteURL:   "https://example.com",
151
	}
152
	posts := []Post{
153
		{
154
			Slug: "hello-world", Title: s("Hello world"), PublishedDate: s("2026-01-02"),
155
			MetaDescription: s("A first post"), Tags: s("go, templ"), Weather: s("{}"),
156
			Content: "Hello **world**", Status: "published",
157
		},
158
		{Slug: "untitled", Content: "A post with no title that runs on for a while", Status: "published"},
159
	}
160
	switch kind {
161
	case "index":
162
		return indexView{siteContext: site, BlogDescription: "A blog", IntroHTML: "<p>Welcome</p>", Posts: posts}
163
	case "post":
164
		return postView{
165
			siteContext: site, Post: posts[0], RenderedContent: "<p>Hello <strong>world</strong></p>",
166
			Weather: Weather{Icon: "<svg></svg>", Conditions: "Sunny", Temperature: "72°F", Location: "Somewhere, OK"},
167
		}
168
	case "page":
169
		return pageView{siteContext: site, Page: Page{Title: "About", Slug: "about", IsPublished: true}, RenderedContent: "<p>About me</p>"}
170
	case "posts":
171
		return postsView{siteContext: site, Posts: posts}
172
	}
173
	return nil
174
}