/
templates.go
106 lines (86 loc) · 2.1 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
package main
import (
"fmt"
"io/fs"
"net/http"
"os"
"path/filepath"
"strings"
"text/template"
"time"
"github.com/gofrs/uuid"
)
var staticURL string = "https://cdn.clacksy.com/file/clacksy"
type templateData struct {
Form any
Flash string
PublicPath string
URLPath string
StaticURL string
AppEnv string
IsAuthenticated bool
PageData any
}
func uuidEq(s string, u uuid.UUID) bool {
return s == u.String()
}
func humanDate(t time.Time) string {
return t.Format("02 Jan 2006 at 3:04PM")
}
func newTemplateCache(files fs.FS) (map[string]*template.Template, error) {
cache := map[string]*template.Template{}
pages, err := fs.Glob(files, "html/pages/*.tmpl")
if err != nil {
return nil, err
}
for _, page := range pages {
name := filepath.Base(page)
patterns := []string{
"html/layout.tmpl",
"html/partials/*.tmpl",
page,
}
funcMap := template.FuncMap{
"uuidEq": uuidEq,
"humanDate": humanDate,
"hasPrefix": strings.HasPrefix,
}
ts, err := template.New(name).Funcs(funcMap).ParseFS(files, patterns...)
if err != nil {
return nil, fmt.Errorf("newTemplateCache: failed to parse template: %w", err)
}
cache[name] = ts
}
return cache, nil
}
func (app *application) newTemplateData(r *http.Request) *templateData {
var publicPath string
appEnv := os.Getenv("APP_ENV")
if appEnv == "production" {
publicPath = staticURL
} else {
publicPath = "/public"
}
return &templateData{
Flash: app.sessionManager.PopString(r.Context(), "flash"),
PublicPath: publicPath,
StaticURL: staticURL,
URLPath: r.URL.Path,
AppEnv: appEnv,
IsAuthenticated: app.isAuthenticated(r),
}
}
func (app *application) renderTemplate(w http.ResponseWriter, statusCode int, page string, data *templateData) {
tmpl, ok := app.templateCache[page]
if !ok {
err := fmt.Errorf("the template %s does not exist", page)
app.serverError(w, err)
return
}
w.WriteHeader(statusCode)
err := tmpl.ExecuteTemplate(w, "layout", data)
if err != nil {
app.serverError(w, err)
return
}
}