-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtemplate.go
329 lines (303 loc) · 8.27 KB
/
template.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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
package kocha
import (
"bytes"
"fmt"
"html/template"
"io"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"github.com/naoina/kocha/util"
)
const (
LayoutDir = "layout"
ErrorTemplateDir = "error"
layoutPath = LayoutDir + string(filepath.Separator)
)
// TemplatePathInfo represents an information of template paths.
type TemplatePathInfo struct {
Name string // name of the application.
Paths []string // directory paths of the template files.
}
type templateKey struct {
appName string
name string
format string
isLayout bool
}
func (k templateKey) String() string {
p := k.name
if k.isLayout {
p = filepath.Join(LayoutDir, p)
}
return fmt.Sprintf("%s:%s.%s", k.appName, p, k.format)
}
// Template represents the templates information.
type Template struct {
PathInfo TemplatePathInfo // information of location of template paths.
FuncMap TemplateFuncMap // same as template.FuncMap.
LeftDelim string // left action delimiter.
RightDelim string // right action delimiter.
m map[templateKey]*template.Template
app *Application
}
// Get gets a parsed template.
func (t *Template) Get(appName, layout, name, format string) (*template.Template, error) {
key := templateKey{
appName: appName,
format: format,
isLayout: layout != "",
}
if key.isLayout {
key.name = layout
} else {
key.name = name
}
tmpl, exists := t.m[key]
if !exists {
return nil, fmt.Errorf("kocha: template not found: %s", key)
}
return tmpl, nil
}
func (t *Template) build(app *Application) (*Template, error) {
if t == nil {
t = &Template{}
}
t.app = app
if t.LeftDelim == "" {
t.LeftDelim = "{{"
}
if t.RightDelim == "" {
t.RightDelim = "}}"
}
t, err := t.buildFuncMap()
if err != nil {
return nil, err
}
t, err = t.buildTemplateMap()
if err != nil {
return nil, err
}
return t, nil
}
func (t *Template) buildFuncMap() (*Template, error) {
m := TemplateFuncMap{
"yield": t.yield,
"in": t.in,
"url": t.url,
"nl2br": t.nl2br,
"raw": t.raw,
"invoke_template": t.invokeTemplate,
"flash": t.flash,
"join": t.join,
}
for name, fn := range t.FuncMap {
m[name] = fn
}
t.FuncMap = m
return t, nil
}
// buildTemplateMap returns templateMap constructed from templateSet.
func (t *Template) buildTemplateMap() (*Template, error) {
info := t.PathInfo
var templatePaths map[string]map[string]map[string]string
if data := t.app.ResourceSet.Get("_kocha_template_paths"); data != nil {
if paths, ok := data.(map[string]map[string]map[string]string); ok {
templatePaths = paths
}
}
if templatePaths == nil {
templatePaths = map[string]map[string]map[string]string{
info.Name: make(map[string]map[string]string),
}
for _, rootPath := range info.Paths {
if err := t.collectTemplatePaths(templatePaths[info.Name], rootPath); err != nil {
return nil, err
}
}
t.app.ResourceSet.Add("_kocha_template_paths", templatePaths)
}
t.m = map[templateKey]*template.Template{}
l := len(t.LeftDelim) + len("$ := .Data") + len(t.RightDelim)
buf := bytes.NewBuffer(append(append(append(make([]byte, 0, l), t.LeftDelim...), "$ := .Data"...), t.RightDelim...))
for appName, templates := range templatePaths {
if err := t.buildAppTemplateSet(buf, l, t.m, appName, templates); err != nil {
return nil, err
}
}
return t, nil
}
// TemplateFuncMap is an alias of templete.FuncMap.
type TemplateFuncMap template.FuncMap
func (t *Template) collectTemplatePaths(templatePaths map[string]map[string]string, templateDir string) error {
return filepath.Walk(templateDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
baseName, err := filepath.Rel(templateDir, path)
if err != nil {
return err
}
name := strings.TrimSuffix(baseName, util.TemplateSuffix)
ext := filepath.Ext(name)
if _, exists := templatePaths[ext]; !exists {
templatePaths[ext] = make(map[string]string)
}
templatePaths[ext][name] = path
return nil
})
}
func (t *Template) buildAppTemplateSet(buf *bytes.Buffer, l int, m map[templateKey]*template.Template, appName string, templates map[string]map[string]string) error {
for ext, templateInfos := range templates {
tmpl := template.New("")
for name, path := range templateInfos {
buf.Truncate(l)
var body string
if data := t.app.ResourceSet.Get(path); data != nil {
if b, ok := data.(string); ok {
buf.WriteString(b)
body = buf.String()
}
} else {
f, err := os.Open(path)
if err != nil {
return err
}
_, err = io.Copy(buf, f)
f.Close()
if err != nil {
return err
}
body = buf.String()
t.app.ResourceSet.Add(path, body)
}
if _, err := tmpl.New(name).Delims(t.LeftDelim, t.RightDelim).Funcs(template.FuncMap(t.FuncMap)).Parse(body); err != nil {
return err
}
}
for _, t := range tmpl.Templates() {
key := templateKey{
appName: appName,
name: strings.TrimSuffix(t.Name(), ext),
format: ext[1:], // truncate the leading dot.
}
if strings.HasPrefix(key.name, layoutPath) {
key.isLayout = true
key.name = key.name[len(layoutPath):]
}
m[key] = t
}
}
return nil
}
func (t *Template) yield(c *Context) (template.HTML, error) {
tmpl, err := t.Get(t.app.Config.AppName, "", c.Name, c.Format)
if err != nil {
return "", err
}
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufPool.Put(buf)
}()
if err := tmpl.Execute(buf, c); err != nil {
return "", err
}
return template.HTML(buf.String()), nil
}
// in is for "in" template function.
func (t *Template) in(a, b interface{}) (bool, error) {
v := reflect.ValueOf(a)
switch v.Kind() {
case reflect.Slice, reflect.Array, reflect.String:
if v.IsNil() {
return false, nil
}
for i := 0; i < v.Len(); i++ {
if v.Index(i).Interface() == b {
return true, nil
}
}
default:
return false, fmt.Errorf("valid types are slice, array and string, got `%s'", v.Kind())
}
return false, nil
}
// url is for "url" template function.
func (t *Template) url(name string, v ...interface{}) (string, error) {
return t.app.Router.Reverse(name, v...)
}
// nl2br is for "nl2br" template function.
func (t *Template) nl2br(text string) template.HTML {
return template.HTML(strings.Replace(template.HTMLEscapeString(text), "\n", "<br>", -1))
}
// raw is for "raw" template function.
func (t *Template) raw(text string) template.HTML {
return template.HTML(text)
}
// invokeTemplate is for "invoke_template" template function.
func (t *Template) invokeTemplate(unit Unit, tmplName, defTmplName string, ctx ...*Context) (html template.HTML, err error) {
var c *Context
switch len(ctx) {
case 0: // do nothing.
case 1:
c = ctx[0]
default:
return "", fmt.Errorf("number of context must be 0 or 1")
}
t.app.Invoke(unit, func() {
if html, err = t.readPartialTemplate(tmplName, c); err != nil {
// TODO: logging error.
panic(ErrInvokeDefault)
}
}, func() {
html, err = t.readPartialTemplate(defTmplName, c)
})
return html, err
}
// flash is for "flash" template function.
// This is a shorthand for {{.Flash.Get "success"}} in template.
func (t *Template) flash(c *Context, key string) string {
return c.Flash.Get(key)
}
// join is for "join" template function.
func (t *Template) join(a interface{}, sep string) (string, error) {
v := reflect.ValueOf(a)
switch v.Kind() {
case reflect.Slice, reflect.Array:
// do nothing.
default:
return "", fmt.Errorf("valid types of first argument are slice or array, got `%s'", v.Kind())
}
if v.Len() == 0 {
return "", nil
}
buf := append(make([]byte, 0, v.Len()*2-1), fmt.Sprint(v.Index(0).Interface())...)
for i := 1; i < v.Len(); i++ {
buf = append(append(buf, sep...), fmt.Sprint(v.Index(i).Interface())...)
}
return string(buf), nil
}
func (t *Template) readPartialTemplate(name string, c *Context) (template.HTML, error) {
tmpl, err := t.Get(t.app.Config.AppName, "", name, "html")
if err != nil {
return "", err
}
buf := bufPool.Get().(*bytes.Buffer)
defer func() {
buf.Reset()
bufPool.Put(buf)
}()
if err := tmpl.Execute(buf, c); err != nil {
return "", err
}
return template.HTML(buf.String()), nil
}
func errorTemplateName(code int) string {
return filepath.Join(ErrorTemplateDir, strconv.Itoa(code))
}