forked from hoisie/mustache
/
mustache.go
425 lines (358 loc) · 11 KB
/
mustache.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
package mustache
import (
"bytes"
"container/vector"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"reflect"
"strings"
)
type textElement struct {
text []byte
}
type varElement struct {
name string
}
type sectionElement struct {
name string
startline int
elems *vector.Vector
}
type template struct {
data string
otag string
ctag string
p int
curline int
dir string
elems *vector.Vector
}
type parseError struct {
line int
message string
}
func (p parseError) String() string { return fmt.Sprintf("line %d: %s", p.line, p.message) }
func (tmpl *template) readString(s string) (string, os.Error) {
i := tmpl.p
newlines := 0
for true {
//are we at the end of the string?
if i+len(s) > len(tmpl.data) {
return tmpl.data[tmpl.p:], os.EOF
}
if tmpl.data[i] == '\n' {
newlines++
}
if tmpl.data[i] != s[0] {
i++
continue
}
match := true
for j := 1; j < len(s); j++ {
if s[j] != tmpl.data[i+j] {
match = false
break
}
}
if match {
e := i + len(s)
text := tmpl.data[tmpl.p:e]
tmpl.p = e
tmpl.curline += newlines
return text, nil
} else {
i++
}
}
//should never be here
return "", nil
}
func (tmpl *template) parsePartial(name string) (*template, os.Error) {
filename := path.Join(tmpl.dir, name+".mustache")
partial, err := ParseFile(filename)
if err != nil {
return nil, err
}
return partial, nil
}
func (tmpl *template) parseSection(section *sectionElement) os.Error {
for {
text, err := tmpl.readString(tmpl.otag)
if err == os.EOF {
return parseError{section.startline, "Section " + section.name + " has no closing tag"}
}
// put text into an item
text = text[0 : len(text)-len(tmpl.otag)]
section.elems.Push(&textElement{[]byte(text)})
text, err = tmpl.readString(tmpl.ctag)
if err == os.EOF {
//put the remaining text in a block
return parseError{tmpl.curline, "unmatched open tag"}
}
//trim the close tag off the text
tag := strings.TrimSpace(text[0 : len(text)-len(tmpl.ctag)])
if len(tag) == 0 {
return parseError{tmpl.curline, "empty tag"}
}
switch tag[0] {
case '!':
//ignore comment
break
case '#':
name := strings.TrimSpace(tag[1:])
//ignore the newline when a section starts
if len(tmpl.data) > tmpl.p && tmpl.data[tmpl.p] == '\n' {
tmpl.p += 1
} else if len(tmpl.data) > tmpl.p+1 && tmpl.data[tmpl.p] == '\r' && tmpl.data[tmpl.p+1] == '\n' {
tmpl.p += 2
}
se := sectionElement{name, tmpl.curline, new(vector.Vector)}
err := tmpl.parseSection(&se)
if err != nil {
return err
}
section.elems.Push(&se)
case '/':
name := strings.TrimSpace(tag[1:])
if name != section.name {
return parseError{tmpl.curline, "interleaved closing tag: " + name}
} else {
return nil
}
case '>':
name := strings.TrimSpace(tag[1:])
partial, err := tmpl.parsePartial(name)
if err != nil {
return err
}
tmpl.elems.Push(partial)
case '=':
if tag[len(tag)-1] != '=' {
panic("Invalid meta tag")
}
tag = strings.TrimSpace(tag[1 : len(tag)-1])
newtags := strings.Split(tag, " ", 0)
if len(newtags) == 2 {
tmpl.otag = newtags[0]
tmpl.ctag = newtags[1]
}
default:
section.elems.Push(&varElement{tag})
}
}
return nil
}
func (tmpl *template) parse() os.Error {
for {
text, err := tmpl.readString(tmpl.otag)
if err == os.EOF {
//put the remaining text in a block
tmpl.elems.Push(&textElement{[]byte(text)})
return nil
}
// put text into an item
text = text[0 : len(text)-len(tmpl.otag)]
tmpl.elems.Push(&textElement{[]byte(text)})
text, err = tmpl.readString(tmpl.ctag)
if err == os.EOF {
//put the remaining text in a block
return parseError{tmpl.curline, "unmatched open tag"}
}
//trim the close tag off the text
tag := strings.TrimSpace(text[0 : len(text)-len(tmpl.ctag)])
if len(tag) == 0 {
return parseError{tmpl.curline, "empty tag"}
}
switch tag[0] {
case '!':
//ignore comment
break
case '#':
name := strings.TrimSpace(tag[1:])
if len(tmpl.data) > tmpl.p && tmpl.data[tmpl.p] == '\n' {
tmpl.p += 1
} else if len(tmpl.data) > tmpl.p+1 && tmpl.data[tmpl.p] == '\r' && tmpl.data[tmpl.p+1] == '\n' {
tmpl.p += 2
}
se := sectionElement{name, tmpl.curline, new(vector.Vector)}
err := tmpl.parseSection(&se)
if err != nil {
return err
}
tmpl.elems.Push(&se)
case '/':
return parseError{tmpl.curline, "unmatched close tag"}
case '>':
name := strings.TrimSpace(tag[1:])
partial, err := tmpl.parsePartial(name)
if err != nil {
return err
}
tmpl.elems.Push(partial)
case '=':
if tag[len(tag)-1] != '=' {
panic("Invalid meta tag")
}
tag = strings.TrimSpace(tag[1 : len(tag)-1])
newtags := strings.Split(tag, " ", 0)
if len(newtags) == 2 {
tmpl.otag = newtags[0]
tmpl.ctag = newtags[1]
}
default:
tmpl.elems.Push(&varElement{tag})
}
}
return nil
}
func lookupMethod(t reflect.Type, name string) *reflect.Method {
for i := 0; i < t.NumMethod(); i++ {
m := t.Method(i)
// fmt.Printf("%v: %d: %s\n", t, i, m.Name)
if name == m.Name {
return &m
}
}
return nil
}
func lookup(context reflect.Value, name string) reflect.Value {
//if the context is an interface, get the actual value
if iface, ok := context.(*reflect.InterfaceValue); ok && !iface.IsNil() {
context = iface.Elem()
}
//the context may be a pointer, so do an indirect
contextInd := reflect.Indirect(context)
var ret reflect.Value = nil
switch val := contextInd.(type) {
case *reflect.MapValue:
ret = val.Elem(reflect.NewValue(name))
case *reflect.StructValue:
ret = val.FieldByName(name)
if nil == ret {
t := val.Type()
// fmt.Printf("\n\nNo field %s found. Trying: %s\n", name, t)
m := lookupMethod(t, name)
if nil == m {
t := context.Type()
// fmt.Printf("Unlucky... trying: %s\n", t)
m = lookupMethod(t, name)
if nil == m {
// fmt.Printf("No luck at all.\n")
if '*' != t.Name()[0] {
fmt.Printf("Warning: Passing a Value type (%v) might hide some method declarations.\n", val.Type())
}
return ret
}
// fmt.Printf("NumArgs: %d\n", m.Type.NumIn())
ret = m.Func.Call([]reflect.Value{context})[0]
// fmt.Printf("result of calling: %v\n", ret)
} else {
// fmt.Printf("NumArgs: %d\n", m.Type.NumIn())
ret = m.Func.Call([]reflect.Value{val})[0]
// fmt.Printf("result of calling: %v\n", ret)
}
}
}
//if the lookup value is an interface, return the actual value
if iface, ok := ret.(*reflect.InterfaceValue); ok && !iface.IsNil() {
ret = iface.Elem()
}
return ret
}
func renderSection(section *sectionElement, context reflect.Value, buf io.Writer) {
value := lookup(context, section.name)
valueInd := reflect.Indirect(value)
var contexts = new(vector.Vector)
switch val := valueInd.(type) {
case *reflect.BoolValue:
if !val.Get() {
return
} else {
contexts.Push(context)
}
case *reflect.SliceValue:
for i := 0; i < val.Len(); i++ {
contexts.Push(val.Elem(i))
}
case *reflect.ArrayValue:
for i := 0; i < val.Len(); i++ {
contexts.Push(val.Elem(i))
}
default:
contexts.Push(context)
}
//by default we execute the section
for j := 0; j < contexts.Len(); j++ {
ctx := contexts.At(j).(reflect.Value)
for i := 0; i < section.elems.Len(); i++ {
renderElement(section.elems.At(i), ctx, buf)
}
}
}
func renderElement(element interface{}, context reflect.Value, buf io.Writer) {
switch elem := element.(type) {
case *textElement:
buf.Write(elem.text)
case *varElement:
val := lookup(context, elem.name)
if val != nil {
fmt.Fprint(buf, val.Interface())
}
case *sectionElement:
renderSection(elem, context, buf)
case *template:
elem.renderTemplate(context, buf)
}
}
func (tmpl *template) renderTemplate(context reflect.Value, buf io.Writer) {
for i := 0; i < tmpl.elems.Len(); i++ {
renderElement(tmpl.elems.At(i), context, buf)
}
}
func (tmpl *template) Render(context interface{}, buf io.Writer) {
val := reflect.NewValue(context)
tmpl.renderTemplate(val, buf)
}
func ParseString(data string) (*template, os.Error) {
cwd := os.Getenv("CWD")
tmpl := template{data, "{{", "}}", 0, 1, cwd, new(vector.Vector)}
err := tmpl.parse()
if err != nil {
return nil, err
}
return &tmpl, err
}
func ParseFile(filename string) (*template, os.Error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
dirname, _ := path.Split(filename)
tmpl := template{string(data), "{{", "}}", 0, 1, dirname, new(vector.Vector)}
err = tmpl.parse()
if err != nil {
return nil, err
}
return &tmpl, nil
}
func Render(data string, context interface{}) (string, os.Error) {
tmpl, err := ParseString(data)
if err != nil {
return "", err
}
var buf bytes.Buffer
tmpl.Render(context, &buf)
return buf.String(), nil
}
func RenderFile(filename string, context interface{}) (string, os.Error) {
tmpl, err := ParseFile(filename)
if err != nil {
return "", err
}
var buf bytes.Buffer
tmpl.Render(context, &buf)
return buf.String(), nil
}