-
Notifications
You must be signed in to change notification settings - Fork 0
/
templates.go
107 lines (87 loc) · 2.4 KB
/
templates.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
package main
import (
"bytes"
"fmt"
"html/template"
"io/fs"
"net/http"
"path/filepath"
"github.com/patrickarmengol/coffeetanuki/internal/data"
"github.com/patrickarmengol/coffeetanuki/internal/validator"
"github.com/patrickarmengol/coffeetanuki/ui"
)
type templateData struct {
Bean *data.Bean
Beans []*data.Bean
Roaster *data.Roaster
Roasters []*data.Roaster
SearchQuery *data.SearchQuery
User *data.User
Validator *validator.Validator
Result bool
IsAuthenticated bool
}
var functions = template.FuncMap{}
func (app *application) newTemplateData(r *http.Request) *templateData {
return &templateData{
IsAuthenticated: app.isAuthenticated(r),
}
}
func newTemplateCache() (map[string]*template.Template, error) {
cache := map[string]*template.Template{}
// get list of pages
pages, err := fs.Glob(ui.Files, "html/pages/*.gohtml")
if err != nil {
return nil, err
}
for _, page := range pages {
name := filepath.Base(page)
// list of template files we want to parse together
patterns := []string{
"html/base.gohtml",
"html/partials/*.gohtml",
page,
}
// register funcmap and parse template files
ts, err := template.New(name).Funcs(functions).ParseFS(ui.Files, patterns...)
if err != nil {
return nil, err
}
cache[name] = ts
}
// get list of partials
partials, err := fs.Glob(ui.Files, "html/partials/*.gohtml")
if err != nil {
return nil, err
}
for _, part := range partials {
name := filepath.Base(part)
ts, err := template.New(name).Funcs(functions).ParseFS(ui.Files, part)
if err != nil {
return nil, err
}
cache[name] = ts
}
return cache, nil
}
func (app *application) render(w http.ResponseWriter, r *http.Request, status int, fileName string, templateName string, data *templateData) {
// retrieve desired template from cache
ts, ok := app.templateCache[fileName]
if !ok {
err := fmt.Errorf("the template at %s does not exist", fileName)
app.serverErrorResponse(w, r, err)
return
}
// initialize a buffer, in case of errors executing template
buf := new(bytes.Buffer)
// execute template, passing data, and writing to buffer
// data is currently a pointer to allow for nil; may change later
err := ts.ExecuteTemplate(buf, templateName, data)
if err != nil {
app.serverErrorResponse(w, r, err)
return
}
// respond with buffer
w.WriteHeader(status)
buf.WriteTo(w)
}