This repository has been archived by the owner on Feb 22, 2019. It is now read-only.
forked from mmurray/go-handlebars
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlebars.go
792 lines (711 loc) · 22.5 KB
/
handlebars.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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
package handlebars
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path"
"reflect"
"strings"
)
type textElement struct {
text []byte
}
type varElement struct {
name string
raw bool
}
type helperElement struct {
name string
params []string
}
type sectionElement struct {
name string
inverted bool
startline int
elems []interface{}
params []string
}
type Template struct {
data string
otag string
ctag string
p int
curline int
dir string
elems []interface{}
}
type parseError struct {
line int
message string
}
func (p parseError) Error() string { return fmt.Sprintf("line %d: %s", p.line, p.message) }
var (
esc_quot = []byte(""")
esc_apos = []byte("'")
esc_amp = []byte("&")
esc_lt = []byte("<")
esc_gt = []byte(">")
)
// taken from pkg/template
func htmlEscape(w io.Writer, s []byte) {
var esc []byte
last := 0
for i, c := range s {
switch c {
case '"':
esc = esc_quot
case '\'':
esc = esc_apos
case '&':
esc = esc_amp
case '<':
esc = esc_lt
case '>':
esc = esc_gt
default:
continue
}
w.Write(s[last:i])
w.Write(esc)
last = i + 1
}
w.Write(s[last:])
}
func (tmpl *Template) readString(s string) (string, 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:], io.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, error) {
filenames := []string{
path.Join(tmpl.dir, name),
path.Join(tmpl.dir, name+".hbs"),
path.Join(tmpl.dir, name+".html.hbs"),
name,
name + ".hbs",
name + ".html.hbs",
}
var filename string
for _, name := range filenames {
f, err := os.Open(name)
if err == nil {
filename = name
f.Close()
break
}
}
if filename == "" {
return nil, errors.New(fmt.Sprintf("Could not find partial %q", name))
}
partial, err := ParseFile(filename)
if err != nil {
return nil, err
}
return partial, nil
}
func (tmpl *Template) parseSection(section *sectionElement) error {
for {
text, err := tmpl.readString(tmpl.otag)
if err == io.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 = append(section.elems, &textElement{[]byte(text)})
if tmpl.p < len(tmpl.data) && tmpl.data[tmpl.p] == '{' {
text, err = tmpl.readString("}" + tmpl.ctag)
} else {
text, err = tmpl.readString(tmpl.ctag)
}
if err == io.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
}
params := make([]string, 0)
nameSections := strings.Split(name, " ")
if (len(nameSections) > 1) {
name = nameSections[0]
params = nameSections[1:]
}
se := sectionElement{
name: name,
inverted: tag[0] == '^',
startline: tmpl.curline,
elems: []interface{}{},
params: params,
}
err := tmpl.parseSection(&se)
if err != nil {
return err
}
section.elems = append(section.elems, &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
}
section.elems = append(section.elems, partial)
case '=':
if tag[len(tag)-1] != '=' {
return parseError{tmpl.curline, "Invalid meta tag"}
}
tag = strings.TrimSpace(tag[1 : len(tag)-1])
newtags := strings.SplitN(tag, " ", 2)
if len(newtags) == 2 {
tmpl.otag = newtags[0]
tmpl.ctag = newtags[1]
}
case '{':
if tag[len(tag)-1] == '}' {
//use a raw tag
section.elems = append(section.elems, &varElement{tag[1 : len(tag)-1], true})
}
default:
section.elems = append(section.elems, &varElement{tag, false})
}
}
return nil
}
func (tmpl *Template) parse() error {
for {
text, err := tmpl.readString(tmpl.otag)
if err == io.EOF {
//put the remaining text in a block
tmpl.elems = append(tmpl.elems, &textElement{[]byte(text)})
return nil
}
// put text into an item
text = text[0 : len(text)-len(tmpl.otag)]
tmpl.elems = append(tmpl.elems, &textElement{[]byte(text)})
if tmpl.p < len(tmpl.data) && tmpl.data[tmpl.p] == '{' {
text, err = tmpl.readString("}" + tmpl.ctag)
} else {
text, err = tmpl.readString(tmpl.ctag)
}
if err == io.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
}
params := make([]string, 0)
nameSections := strings.Split(name, " ")
if (len(nameSections) > 1) {
name = nameSections[0]
params = nameSections[1:]
}
se := sectionElement{
name: name,
inverted: tag[0] == '^',
startline: tmpl.curline,
elems: []interface{}{},
params: params,
}
err := tmpl.parseSection(&se)
if err != nil {
return err
}
tmpl.elems = append(tmpl.elems, &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 = append(tmpl.elems, partial)
case '=':
if tag[len(tag)-1] != '=' {
return parseError{tmpl.curline, "Invalid meta tag"}
}
tag = strings.TrimSpace(tag[1 : len(tag)-1])
newtags := strings.SplitN(tag, " ", 2)
if len(newtags) == 2 {
tmpl.otag = newtags[0]
tmpl.ctag = newtags[1]
}
case '{':
//use a raw tag
if tag[len(tag)-1] == '}' {
tmpl.elems = append(tmpl.elems, &varElement{tag[1 : len(tag)-1], true})
}
default:
tmpl.elems = append(tmpl.elems, &varElement{tag, false})
}
}
return nil
}
// See if name is a method of the value at some level of indirection.
// The return values are the result of the call (which may be nil if
// there's trouble) and whether a method of the right name exists with
// any signature.
func callMethod(data reflect.Value, name string) (result reflect.Value, found bool) {
found = false
// Method set depends on pointerness, and the value may be arbitrarily
// indirect. Simplest approach is to walk down the pointer chain and
// see if we can find the method at each step.
// Most steps will see NumMethod() == 0.
for {
typ := data.Type()
if nMethod := data.Type().NumMethod(); nMethod > 0 {
for i := 0; i < nMethod; i++ {
method := typ.Method(i)
if method.Name == name {
found = true // we found the name regardless
// does receiver type match? (pointerness might be off)
if typ == method.Type.In(0) {
return call(data, method), found
}
}
}
}
if nd := data; nd.Kind() == reflect.Ptr {
data = nd.Elem()
} else {
break
}
}
return
}
// Invoke the method. If its signature is wrong, return nil.
func call(v reflect.Value, method reflect.Method) reflect.Value {
funcType := method.Type
// Method must take no arguments, meaning as a func it has one argument (the receiver)
if funcType.NumIn() != 1 {
return reflect.Value{}
}
// Method must return a single value.
if funcType.NumOut() == 0 {
return reflect.Value{}
}
// Result will be the zeroth element of the returned slice.
return method.Func.Call([]reflect.Value{v})[0]
}
// Evaluate interfaces and pointers looking for a value that can look up the name, via a
// struct field, method, or map key, and return the result of the lookup.
func lookup(contextChain []interface{}, name string) reflect.Value {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Panic while looking up %q: %s\n", name, r)
}
}()
Outer:
for _, ctx := range contextChain { //i := len(contextChain) - 1; i >= 0; i-- {
v := ctx.(reflect.Value)
for v.IsValid() {
typ := v.Type()
if n := v.Type().NumMethod(); n > 0 {
for i := 0; i < n; i++ {
m := typ.Method(i)
mtyp := m.Type
if m.Name == name && mtyp.NumIn() == 1 {
return v.Method(i).Call(nil)[0]
}
}
}
if name == "." || name == "this" {
return v
}
// if helper, ok := helpers[name]; ok {
// return reflect.ValueOf(helper("FOO", "BAR"))
// }
switch av := v; av.Kind() {
case reflect.Ptr:
v = av.Elem()
case reflect.Interface:
v = av.Elem()
case reflect.Struct:
ret := av.FieldByName(name)
if ret.IsValid() {
return ret
} else {
continue Outer
}
case reflect.Map:
ret := av.MapIndex(reflect.ValueOf(name))
if ret.IsValid() {
return ret
} else {
continue Outer
}
default:
continue Outer
}
}
}
return reflect.Value{}
}
func isEmpty(v reflect.Value) bool {
if !v.IsValid() || v.Interface() == nil {
return true
}
valueInd := indirect(v)
if !valueInd.IsValid() {
return true
}
switch val := valueInd; val.Kind() {
case reflect.Bool:
return !val.Bool()
case reflect.Slice:
return val.Len() == 0
}
return false
}
func indirect(v reflect.Value) reflect.Value {
loop:
for v.IsValid() {
switch av := v; av.Kind() {
case reflect.Ptr:
v = av.Elem()
case reflect.Interface:
v = av.Elem()
default:
break loop
}
}
return v
}
func renderSection(section *sectionElement, contextChain []interface{}, buf io.Writer) {
value := lookup(contextChain, section.name)
var context = contextChain[len(contextChain)-1].(reflect.Value)
var contexts = []interface{}{}
if handler, ok := helpers[section.name]; ok {
var stringBuf bytes.Buffer
if len(section.elems) >= 1 {
/* chain2 := make([]interface{}, len(contextChain)+1)
copy(chain2[1:], contextChain)
for _, ctx := range contexts {
chain2[0] = ctx
for _, elem := range section.elems {
renderElement(elem, chain2, &stringBuf)
}
}*/
for _, elem := range section.elems {
renderElement(elem, contextChain, &stringBuf)
}
params := make([]interface{}, 0)
for _, piece := range section.params {
param := fmt.Sprintf("%v", piece)
if param == "this" {
param = `.`
}
if len(param) > 1 && param[0] == '"' && param[len(param) - 1] == '"' {
params = append(params, param[1:len(param)-1])
} else {
paramVal := lookup(contextChain, param)
if paramVal.IsValid() {
params = append(params, paramVal.Interface())
}
}
}
params = append(params, stringBuf.String())
renderElement(&textElement{
text: []byte(handler(params...)),
}, contextChain, buf);
}
return
}
// if the value is nil, check if it's an inverted section
isEmpty := isEmpty(value)
if isEmpty && !section.inverted || !isEmpty && section.inverted {
return
} else if !section.inverted {
valueInd := indirect(value)
switch val := valueInd; val.Kind() {
case reflect.Slice:
for i := 0; i < val.Len(); i++ {
contexts = append(contexts, val.Index(i))
}
case reflect.Array:
for i := 0; i < val.Len(); i++ {
contexts = append(contexts, val.Index(i))
}
case reflect.Map, reflect.Struct:
contexts = append(contexts, value)
default:
contexts = append(contexts, context)
}
} else if section.inverted {
contexts = append(contexts, context)
}
chain2 := make([]interface{}, len(contextChain)+1)
copy(chain2[1:], contextChain)
//by default we execute the section
for _, ctx := range contexts {
chain2[0] = ctx
for _, elem := range section.elems {
renderElement(elem, chain2, buf)
}
}
}
func renderElement(element interface{}, contextChain []interface{}, buf io.Writer) {
switch elem := element.(type) {
case *textElement:
buf.Write(elem.text)
case *varElement:
defer func() {
if r := recover(); r != nil {
fmt.Printf("Panic while looking up %q: %s\n", elem.name, r)
}
}()
elPieces := strings.Split(elem.name, " ")
var val reflect.Value
params := []reflect.Value{}
if len(elPieces) > 1 {
if helper, ok := helpers[elPieces[0]]; ok {
params := make([]interface{}, 0)
if len(elPieces) > 1 {
for _, piece := range elPieces[1:] {
param := fmt.Sprintf("%v", piece)
if param == "this" {
param = `.`
}
if len(param) > 1 && param[0] == '"' && param[len(param) - 1] == '"' {
params = append(params, param[1:len(param)-1])
} else {
paramVal := lookup(contextChain, param)
if paramVal.IsValid() {
params = append(params, paramVal.Interface())
}
}
}
}
result := helper(params...)
if elem.raw {
fmt.Fprintf(buf, result)
} else {
htmlEscape(buf, []byte(result))
}
return
} else {
val = lookup(contextChain, elPieces[0])
for _, piece := range elPieces[1:] {
if piece[0] == '"' && piece[len(piece)-1] == '"' {
// is a string param
params = append(params, reflect.ValueOf(piece[1:len(piece)-1]))
} else {
var sbuf bytes.Buffer
pv := lookup(contextChain, piece)
if (pv.IsValid()) {
s := fmt.Sprint(pv.Interface())
htmlEscape(&sbuf, []byte(s))
params = append(params, reflect.ValueOf(sbuf.String()))
}
}
}
}
} else {
pathPieces := strings.Split(elem.name, ".")
if len(pathPieces) > 1 {
// looks like a path
curVal := lookup(contextChain, pathPieces[0])
for i, _ := range pathPieces {
if i == len(pathPieces) - 1 {
// TODO: HTML escape?
val = curVal
break
}
if curVal.IsValid() {
indVal := indirect(curVal)
if indVal.IsValid() && indVal.Kind() == reflect.Map {
curVal = indVal.MapIndex(reflect.ValueOf(pathPieces[i+1]))
}
}
}
} else {
// not a path or helper, just lookup value by key normally
val = lookup(contextChain, elem.name)
}
}
if val.IsValid() {
if elem.raw {
fmt.Fprint(buf, val.Interface())
} else {
var s string
if(indirect(val).Type().Kind() == reflect.Func) {
s = fmt.Sprint(indirect(val).Call(params)[0])
} else {
s = fmt.Sprint(val.Interface())
}
htmlEscape(buf, []byte(s))
}
}
case *sectionElement:
renderSection(elem, contextChain, buf)
case *Template:
elem.renderTemplate(contextChain, buf)
}
}
func (tmpl *Template) renderTemplate(contextChain []interface{}, buf io.Writer) {
for _, elem := range tmpl.elems {
renderElement(elem, contextChain, buf)
}
}
func (tmpl *Template) Render(context ...interface{}) string {
var buf bytes.Buffer
var contextChain []interface{}
for _, c := range context {
val := reflect.ValueOf(c)
contextChain = append(contextChain, val)
}
tmpl.renderTemplate(contextChain, &buf)
return buf.String()
}
func (tmpl *Template) RenderInLayout(layout *Template, context ...interface{}) string {
content := tmpl.Render(context...)
allContext := make([]interface{}, len(context)+1)
copy(allContext[1:], context)
allContext[0] = map[string]string{"content": content}
return layout.Render(allContext...)
}
func ParseString(data string) (*Template, error) {
cwd := os.Getenv("CWD")
tmpl := Template{data, "{{", "}}", 0, 1, cwd, []interface{}{}}
err := tmpl.parse()
if err != nil {
return nil, err
}
return &tmpl, err
}
func ParseFile(filename string) (*Template, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
dirname, _ := path.Split(filename)
tmpl := Template{string(data), "{{", "}}", 0, 1, dirname, []interface{}{}}
err = tmpl.parse()
if err != nil {
return nil, err
}
return &tmpl, nil
}
func Render(data string, context ...interface{}) string {
tmpl, err := ParseString(data)
if err != nil {
return err.Error()
}
return tmpl.Render(context...)
}
func RenderInLayout(data string, layoutData string, context ...interface{}) string {
layoutTmpl, err := ParseString(layoutData)
if err != nil {
return err.Error()
}
tmpl, err := ParseString(data)
if err != nil {
return err.Error()
}
return tmpl.RenderInLayout(layoutTmpl, context...)
}
func RenderFile(filename string, context ...interface{}) string {
tmpl, err := ParseFile(filename)
if err != nil {
return err.Error()
}
return tmpl.Render(context...)
}
func RenderFileInLayout(filename string, layoutFile string, context ...interface{}) string {
layoutTmpl, err := ParseFile(layoutFile)
if err != nil {
return err.Error()
}
tmpl, err := ParseFile(filename)
if err != nil {
return err.Error()
}
return tmpl.RenderInLayout(layoutTmpl, context...)
}
type helperFn func(p ...interface{}) string
var helpers = make(map[string]helperFn)
func RegisterHelper(name string, helper helperFn) {
helpers[name] = helper
}
var content = make(map[string]*Template)
func RegisterContent(name string, data string) error {
dirname, _ := path.Split(name)
tmpl := Template{string(data), "{{", "}}", 0, 1, dirname, []interface{}{}}
err := tmpl.parse()
if err != nil {
return err
}
content[name] = &tmpl
return nil
}
func ContentFor(name string) (*Template, bool) {
tmpl, ok := content[name]
return tmpl, ok
}