-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathviews.go
More file actions
174 lines (158 loc) · 5.9 KB
/
Copy pathviews.go
File metadata and controls
174 lines (158 loc) · 5.9 KB
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
// Copyright 2015 Eryx <evorui at gmail dot com>, All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package httpsrv
import (
"bytes"
"fmt"
"html/template"
"io"
"io/fs"
"os"
"path"
"strings"
"time"
)
// Views is the interface that wraps the Render function. A template engine
// implements it so Handler code can call Ctx.Render. The built-in engine
// satisfies it; plug in a custom engine via WithViews.
//
// Default: nil
type Views interface {
// Load is called once to load/parse templates. The built-in engine
// parses at construction, so its Load is a no-op.
Load() error
// Render writes the named template (with optional layouts) to w.
Render(w io.Writer, name string, bind any, layout ...string) error
}
// TemplatesFS builds a template engine from fsys (e.g. an embed.FS after
// fs.Sub) and returns it as a Views. All .html/.tpl files are parsed
// immediately, so {{template "x"}} includes work.
func TemplatesFS(fsys fs.FS, extraFuncs template.FuncMap) (Views, error) {
r := &renderer{fsys: fsys}
r.set = template.New("").Funcs(builtinFuncs())
if extraFuncs != nil {
r.set = r.set.Funcs(extraFuncs)
}
if err := r.loadAll(); err != nil {
return nil, err
}
return r, nil
}
// TemplatesDir builds a template engine from the filesystem directory at root
// and returns it as a Views.
func TemplatesDir(root string, extraFuncs template.FuncMap) (Views, error) {
return TemplatesFS(os.DirFS(root), extraFuncs)
}
// renderer is the built-in template engine. It parses html/template files from
// a filesystem (a directory via TemplatesDir, or an embed/other fs.FS via
// TemplatesFS) once at construction, then renders them by name with optional
// layouts. Built-in template functions (raw, replace, upper, lower, date,
// datetime) are always available; pass extraFuncs to add more (e.g. an I18n
// store's Funcs() to get T). *renderer implements Views. It is unexported:
// callers obtain it as a Views via TemplatesDir/TemplatesFS and never need to
// name the concrete type.
type renderer struct {
fsys fs.FS
set *template.Template // shared, parsed set (read-only after construction)
}
// Load is a no-op: templates are parsed once at construction (TemplatesFS/
// TemplatesDir), so by the time an engine is attached there is nothing left
// to load. It satisfies the Views interface.
func (r *renderer) Load() error { return nil }
// Render renders name with bind into w, wrapping the output in each layout in
// order (the last layout is the outermost). It implements Views.
func (r *renderer) Render(w io.Writer, name string, bind any, layout ...string) error {
return r.execute(w, name, bind, layout...)
}
// loadAll parses every .html/.tpl file under the root into the shared set.
func (r *renderer) loadAll() error {
return fs.WalkDir(r.fsys, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if !(strings.HasSuffix(p, ".html") || strings.HasSuffix(p, ".tpl")) {
return nil
}
data, err := fs.ReadFile(r.fsys, p)
if err != nil {
return fmt.Errorf("read template %s: %w", p, err)
}
name := strings.TrimPrefix(p, "./")
if _, err := r.set.New(name).Parse(string(data)); err != nil {
return fmt.Errorf("parse template %s: %w", p, err)
}
return nil
})
}
// execute renders name with bind, wrapping the output in each layout in order
// (the last layout is the outermost). Each layout receives a map whose "Content"
// key holds the inner rendered HTML; when bind is a map, its entries are merged
// in (so layouts can use the same fields as the content template).
func (r *renderer) execute(w io.Writer, name string, bind any, layouts ...string) error {
name = cleanTemplateName(name)
if r.set.Lookup(name) == nil {
return fmt.Errorf("template %q not found", name)
}
var buf bytes.Buffer
if err := r.set.ExecuteTemplate(&buf, name, bind); err != nil {
return err
}
content := buf.String()
for _, l := range layouts {
l = cleanTemplateName(l)
if r.set.Lookup(l) == nil {
return fmt.Errorf("layout %q not found", l)
}
buf.Reset()
if err := r.set.ExecuteTemplate(&buf, l, layoutData(bind, content)); err != nil {
return err
}
content = buf.String()
}
_, err := io.WriteString(w, content)
return err
}
// cleanTemplateName normalizes a template name (leading slash removed, "."/".."
// resolved) to match the names loadAll registered.
func cleanTemplateName(name string) string {
return strings.TrimPrefix(path.Clean("/"+name), "/")
}
func layoutData(bind any, content string) any {
// Content is the rendered inner template (already escaped by its own
// execution), so mark it safe to avoid double-escaping in the layout.
m := map[string]any{"Content": template.HTML(content)}
if bm, ok := bind.(map[string]any); ok {
for k, v := range bm {
if k != "Content" {
m[k] = v
}
}
}
return m
}
// builtinFuncs returns the always-available template functions. i18n (T) is
// opt-in via I18n.Funcs() passed as extraFuncs — it is not loaded by default.
func builtinFuncs() template.FuncMap {
return template.FuncMap{
"raw": func(s string) template.HTML { return template.HTML(s) },
"replace": func(s, old, new string) string { return strings.ReplaceAll(s, old, new) },
"upper": strings.ToUpper,
"lower": strings.ToLower,
"date": func(t time.Time) string { return t.Format("2006-01-02") },
"datetime": func(t time.Time) string { return t.Format("2006-01-02 15:04") },
}
}