-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate-rendering.go
246 lines (224 loc) · 7.46 KB
/
template-rendering.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
// Package godest provides a mildly opinionated framework for more easily writing web apps with
// modest Javascript approaches, especially with the Hotwire libraries. It provides support for
// using templates in a clear and structured way. It also makes it easy to embed all templates,
// static assets (e.g. images) and app-related assets (e.g. JS bundles) into the compiled server
// binary, and it takes care of the details of browser caching for assets and templated pages.
// Finally, it provides some standalone utilities for caching data on the server, getting the values
// of environment variables, and using cookies for form-based authentication.
package godest
import (
"bytes"
"html/template"
"io"
"io/fs"
"net/http"
"github.com/pkg/errors"
"github.com/sargassum-world/godest/turbostreams"
)
type RenderData struct {
Meta struct {
Path string
RequestURI string
}
Inlines interface{}
Data interface{}
Auth interface{}
}
type TemplateRenderer struct {
allTemplates *template.Template
partialTemplates map[string]*template.Template
pageTemplates map[string]*template.Template
turboStreamsTemplate *template.Template
inlines interface{}
fingerprints fingerprints
}
func instantiateTemplates(
templatesFS fs.FS, allTemplates *template.Template, templateFilter func(string) bool,
) (templates map[string]*template.Template, err error) {
templates = make(map[string]*template.Template)
templateFiles, err := listFiles(templatesFS, templateFilter)
if err != nil {
return nil, errors.Wrap(err, "couldn't list templates")
}
for _, name := range templateFiles {
all, err := allTemplates.Clone()
if err != nil {
return nil, errors.Wrap(err, "couldn't clone root template set")
}
templates[name], err = parseFS(all, templatesFS, name)
if err != nil {
return nil, errors.Wrapf(err, "couldn't make template set for %s", name)
}
}
return templates, nil
}
func instantiateTurboStreamsTemplate(
allTemplates *template.Template, turboStreamsTemplate string,
) (t *template.Template, err error) {
all, err := allTemplates.Clone()
if err != nil {
return nil, errors.Wrap(err, "couldn't clone root template set")
}
t, err = all.Parse(turboStreamsTemplate)
if err != nil {
return nil, errors.Wrap(err, "couldn't parse Turbo Streams template")
}
return t, nil
}
func NewTemplateRenderer(
e Embeds, inlines interface{}, funcs ...template.FuncMap,
) (tr TemplateRenderer, err error) {
tmpl := template.New("App")
for _, f := range funcs {
tmpl = tmpl.Funcs(f)
}
tr.allTemplates, err = parseFS(tmpl, e.TemplatesFS, "**/*"+templateFileExt)
if err != nil {
return TemplateRenderer{}, errors.Wrap(err, "couldn't load templates from filesystem")
}
tr.pageTemplates, err = instantiateTemplates(
e.TemplatesFS, tr.allTemplates, filterPageTemplate,
)
if err != nil {
return TemplateRenderer{}, errors.Wrap(err, "couldn't instantiate page templates")
}
tr.partialTemplates, err = instantiateTemplates(
e.TemplatesFS, tr.allTemplates, filterPartialTemplate,
)
if err != nil {
return TemplateRenderer{}, errors.Wrap(err, "couldn't instantiate partial templates")
}
tr.turboStreamsTemplate, err = instantiateTurboStreamsTemplate(
tr.allTemplates, turbostreams.Template,
)
if err != nil {
return TemplateRenderer{}, errors.Wrap(err, "couldn't instantiate Turbo Streams template")
}
tr.inlines = inlines
if tr.fingerprints.app, err = e.computeAppFingerprint(); err != nil {
return TemplateRenderer{}, errors.Wrap(err, "couldn't compute fingerprint for app")
}
if tr.fingerprints.page, err = e.computePageFingerprints(); err != nil {
return TemplateRenderer{}, errors.Wrap(
err, "couldn't compute fingerprint for page/module templates",
)
}
return tr, nil
}
func (tr TemplateRenderer) MustHave(templateNames ...string) {
for _, templateName := range templateNames {
if tr.allTemplates.Lookup(templateName) == nil {
panic(errors.Errorf("couldn't find required template %s", templateName))
}
if filterPageTemplate(templateName) {
tr.fingerprints.mustHaveForPage(templateName)
}
}
}
func (tr TemplateRenderer) newRenderData(
r *http.Request, data interface{}, auth interface{},
) RenderData {
return RenderData{
Meta: struct {
Path string
RequestURI string
}{
Path: r.URL.Path,
RequestURI: r.URL.RequestURI(),
},
Inlines: tr.inlines,
Data: data,
Auth: auth,
}
}
func (tr TemplateRenderer) Page(
w http.ResponseWriter, r *http.Request,
status int, templateName string, templateData interface{}, authData interface{},
headerOptions ...HeaderOption,
) error {
// This is basically a reimplementation of the echo.Context.Render method, but without requiring
// an echo.Context to be provided
buf := new(bytes.Buffer)
tmpl, ok := tr.pageTemplates[templateName]
if !ok {
return errors.Errorf("page template %s not found", templateName)
}
if err := tmpl.ExecuteTemplate(
buf, templateName, tr.newRenderData(r, templateData, authData),
); err != nil {
return errors.Wrapf(err, "couldn't execute page template %s", templateName)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
for _, headerOption := range headerOptions {
headerOption(w.Header())
}
w.WriteHeader(status)
_, werr := w.Write(buf.Bytes())
return werr
}
func (tr TemplateRenderer) CacheablePage(
w http.ResponseWriter, r *http.Request,
templateName string, templateData interface{}, authData interface{},
headerOptions ...HeaderOption,
) error {
type EtagInputs struct {
Data interface{}
Auth interface{}
}
if noContent, err := tr.fingerprints.setAndCheckEtag(w, r, templateName, EtagInputs{
Data: templateData,
Auth: authData,
}); noContent || (err != nil) {
return err
}
return tr.Page(w, r, http.StatusOK, templateName, templateData, authData, headerOptions...)
}
func (tr TemplateRenderer) WritePartial(
w io.Writer, partialName string, partialData interface{},
) error {
tmpl, ok := tr.partialTemplates[partialName]
if !ok {
return errors.Errorf("partial template %s not found", partialName)
}
if err := tmpl.ExecuteTemplate(w, partialName, partialData); err != nil {
return errors.Wrapf(err, "couldn't execute partial template %s", partialName)
}
return nil
}
type renderedStreamMessage struct {
Action turbostreams.Action
Targets string
Target string
Rendered template.HTML
}
func (tr TemplateRenderer) WriteTurboStream(w io.Writer, messages ...turbostreams.Message) error {
rendered := make([]renderedStreamMessage, len(messages))
for i, message := range messages {
buf := new(bytes.Buffer)
if message.Action != turbostreams.ActionRemove {
if err := tr.WritePartial(buf, message.Template, message.Data); err != nil {
return errors.Wrapf(err, "couldn't execute stream message template %s", message.Template)
}
}
rendered[i] = renderedStreamMessage{
Action: message.Action,
Targets: message.Targets,
Target: message.Target,
//nolint:gosec // This is generated from trusted templates, so we know it's well-formed
Rendered: template.HTML(buf.String()),
}
}
buf := new(bytes.Buffer)
if err := tr.turboStreamsTemplate.Execute(buf, rendered); err != nil {
return errors.Wrap(err, "couldn't execute Turbo Streams message template")
}
_, werr := w.Write(buf.Bytes())
return werr
}
func (tr TemplateRenderer) TurboStream(
w http.ResponseWriter, messages ...turbostreams.Message,
) error {
w.Header().Set("Content-Type", turbostreams.ContentType+"; charset=utf-8")
w.WriteHeader(http.StatusOK)
return tr.WriteTurboStream(w, messages...)
}