forked from aymerick/raymond
-
Notifications
You must be signed in to change notification settings - Fork 0
/
raymond_test.go
115 lines (90 loc) · 2.07 KB
/
raymond_test.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
package raymond
import "fmt"
func Example() {
source := "<h1>{{title}}</h1><p>{{body.content}}</p>"
ctx := map[string]interface{}{
"title": "foo",
"body": map[string]string{"content": "bar"},
}
// parse template
tpl := MustParse(source)
// evaluate template with context
output := tpl.MustExec(ctx)
// alternatively, for one shots:
// output := MustRender(source, ctx)
fmt.Print(output)
// Output: <h1>foo</h1><p>bar</p>
}
func Example_struct() {
source := `<div class="post">
<h1>By {{fullName author}}</h1>
<div class="body">{{body}}</div>
<h1>Comments</h1>
{{#each comments}}
<h2>By {{fullName author}}</h2>
<div class="body">{{content}}</div>
{{/each}}
</div>`
type Person struct {
FirstName string
LastName string
}
type Comment struct {
Author Person
Body string `handlebars:"content"`
}
type Post struct {
Author Person
Body string
Comments []Comment
}
ctx := Post{
Person{"Jean", "Valjean"},
"Life is difficult",
[]Comment{
Comment{
Person{"Marcel", "Beliveau"},
"LOL!",
},
},
}
RegisterHelper("fullName", func(person Person) string {
return person.FirstName + " " + person.LastName
})
output := MustRender(source, ctx)
fmt.Print(output)
// Output: <div class="post">
// <h1>By Jean Valjean</h1>
// <div class="body">Life is difficult</div>
//
// <h1>Comments</h1>
//
// <h2>By Marcel Beliveau</h2>
// <div class="body">LOL!</div>
// </div>
}
func ExampleRender() {
tpl := "<h1>{{title}}</h1><p>{{body.content}}</p>"
ctx := map[string]interface{}{
"title": "foo",
"body": map[string]string{"content": "bar"},
}
// render template with context
output, err := Render(tpl, ctx)
if err != nil {
panic(err)
}
fmt.Print(output)
// Output: <h1>foo</h1><p>bar</p>
}
func ExampleMustRender() {
tpl := "<h1>{{title}}</h1><p>{{body.content}}</p>"
ctx := map[string]interface{}{
"title": "foo",
"body": map[string]string{"content": "bar"},
}
// render template with context
output := MustRender(tpl, ctx)
fmt.Print(output)
// Output: <h1>foo</h1><p>bar</p>
}