-
Notifications
You must be signed in to change notification settings - Fork 5
/
example_test.go
99 lines (78 loc) · 2.25 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
// Copyright (c) 2014 Alex Kalyvitis
package mustache
import (
"fmt"
"net/http"
"net/http/httptest"
"os"
)
func ExampleTemplate_basic() {
template := New()
template.ParseString(`{{#foo}}{{bar}}{{/foo}}`)
context := map[string]interface{}{
"foo": true,
"bar": "bazinga!",
}
output, _ := template.RenderString(context)
fmt.Println(output)
// Output: bazinga!
}
func ExampleTemplate_partials() {
partial := New(Name("partial"))
partial.ParseString(`{{bar}}`)
template := New(Partial(partial))
template.ParseString(`{{#foo}}{{>partial}}{{/foo}}`)
context := map[string]interface{}{
"foo": true,
"bar": "bazinga!",
}
template.Render(os.Stdout, context)
// Output: bazinga!
}
func ExampleTemplate_reader() {
f, err := os.Open("template.mustache")
if err != nil {
fmt.Fprintf(os.Stderr, "failed to open file: %s\n", err)
}
t, err := Parse(f)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to parse template: %s\n", err)
}
t.Render(os.Stdout, nil)
}
func ExampleTemplate_http() {
writer := httptest.NewRecorder()
request, _ := http.NewRequest("GET", "http://example.com?foo=bar&bar=one&bar=two", nil)
template := New()
template.ParseString(`
<ul>{{#foo}}<li>{{.}}</li>{{/foo}}</ul>
<ul>{{#bar}}<li>{{.}}</li>{{/bar}}</ul>`)
handler := func(w http.ResponseWriter, r *http.Request) {
template.Render(w, r.URL.Query())
}
handler(writer, request)
fmt.Println(writer.Body.String())
// Output:
// <ul><li>bar</li></ul>
// <ul><li>one</li><li>two</li></ul>
}
func ExampleOption() {
title := New(Name("header")) // instantiate and name the template
title.ParseString("{{title}}") // parse a template string
body := New()
body.Option(Name("body")) // options can be defined after we instantiate too
body.ParseString("{{content}}")
template := New(
Delimiters("|", "|"), // set the mustache delimiters to | instead of {{
SilentMiss(false), // return an error if a variable lookup fails
Partial(title), // register a partial
Partial(body)) // and another one...
template.ParseString("|>header|\n|>body|")
context := map[string]interface{}{
"title": "Mustache",
"content": "Logic less templates with Mustache!",
}
template.Render(os.Stdout, context)
// Output: Mustache
// Logic less templates with Mustache!
}