-
Notifications
You must be signed in to change notification settings - Fork 56
/
example_test.go
114 lines (101 loc) · 1.86 KB
/
example_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
package plush_test
import (
"fmt"
"html/template"
"log"
"github.com/gobuffalo/plush/v5"
)
// ExampleRender using `if`, `for`, `else`, functions, etc...
func ExampleRender() {
html := `<html>
<%= if (names && len(names) > 0) { %>
<ul>
<%= for (n) in names { %>
<li><%= capitalize(n) %></li>
<% } %>
</ul>
<% } else { %>
<h1>Sorry, no names. :(</h1>
<% } %>
</html>`
ctx := plush.NewContext()
ctx.Set("names", []string{"john", "paul", "george", "ringo"})
s, err := plush.Render(html, ctx)
if err != nil {
log.Fatal(err)
}
fmt.Print(s)
// output: <html>
//
// <ul>
//
// <li>John</li>
//
// <li>Paul</li>
//
// <li>George</li>
//
// <li>Ringo</li>
//
// </ul>
//
// </html>
}
func ExampleRender_scripletTags() {
html := `<%
let h = {name: "mark"}
let greet = fn(n) {
return "hi " + n
}
%>
<h1><%= greet(h["name"]) %></h1>`
s, err := plush.Render(html, plush.NewContext())
if err != nil {
log.Fatal(err)
}
fmt.Print(s)
// output:<h1>hi mark</h1>
}
func ExampleRender_customHelperFunctions() {
html := `<p><%= one() %></p>
<p><%= greet("mark")%></p>
<%= can("update") { %>
<p>i can update</p>
<% } %>
<%= can("destroy") { %>
<p>i can destroy</p>
<% } %>
`
ctx := plush.NewContext()
ctx.Set("one", func() int {
return 1
})
ctx.Set("greet", func(s string) string {
return fmt.Sprintf("Hi %s", s)
})
ctx.Set("can", func(s string, help plush.HelperContext) (template.HTML, error) {
if s == "update" {
h, err := help.Block()
return template.HTML(h), err
}
return "", nil
})
s, err := plush.Render(html, ctx)
if err != nil {
log.Fatal(err)
}
fmt.Print(s)
// output: <p>1</p>
// <p>Hi mark</p>
//
// <p>i can update</p>
}
func ExampleRender_forIterator() {
html := `<%= for (v) in between(3,6) { %><%=v%><% } %>`
s, err := plush.Render(html, plush.NewContext())
if err != nil {
log.Fatal(err)
}
fmt.Print(s)
// output: 45
}