1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
22 <meta charset="UTF-8">
23 <title>{{.Title}}</title>
26 {{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}}
30 check
:= func(err error
) {
35 t
, err
:= template
.New("webpage").Parse(tpl
)
49 err
= t
.Execute(os
.Stdout
, data
)
56 Title
: "My another page",
60 err
= t
.Execute(os
.Stdout
, noItems
)
67 // <meta charset="UTF-8">
68 // <title>My page</title>
71 // <div>My photos</div><div>My blog</div>
77 // <meta charset="UTF-8">
78 // <title>My another page</title>
81 // <div><strong>no rows</strong></div>
87 func Example_autoescaping() {
88 check
:= func(err error
) {
93 t
, err
:= template
.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
95 err
= t
.ExecuteTemplate(os
.Stdout
, "T", "<script>alert('you have been pwned')</script>")
98 // Hello, <script>alert('you have been pwned')</script>!
101 func Example_escape() {
102 const s
= `"Fran & Freddie's Diner" <tasty@example.com>`
103 v
:= []interface{}{`"Fran & Freddie's Diner"`, ' ', `<tasty@example.com>`}
105 fmt
.Println(template
.HTMLEscapeString(s
))
106 template
.HTMLEscape(os
.Stdout
, []byte(s
))
107 fmt
.Fprintln(os
.Stdout
, "")
108 fmt
.Println(template
.HTMLEscaper(v
...))
110 fmt
.Println(template
.JSEscapeString(s
))
111 template
.JSEscape(os
.Stdout
, []byte(s
))
112 fmt
.Fprintln(os
.Stdout
, "")
113 fmt
.Println(template
.JSEscaper(v
...))
115 fmt
.Println(template
.URLQueryEscaper(v
...))
118 // "Fran & Freddie's Diner" <tasty@example.com>
119 // "Fran & Freddie's Diner" <tasty@example.com>
120 // "Fran & Freddie's Diner"32<tasty@example.com>
121 // \"Fran & Freddie\'s Diner\" \x3Ctasty@example.com\x3E
122 // \"Fran & Freddie\'s Diner\" \x3Ctasty@example.com\x3E
123 // \"Fran & Freddie\'s Diner\"32\x3Ctasty@example.com\x3E
124 // %22Fran+%26+Freddie%27s+Diner%2232%3Ctasty%40example.com%3E
128 // The following example is duplicated in text/template; keep them in sync.
130 func ExampleTemplate_block() {
132 master
= `Names:{{block "list" .}}{{"\n"}}{{range .}}{{println "-" .}}{{end}}{{end}}`
133 overlay
= `{{define "list"}} {{join . ", "}}{{end}} `
136 funcs
= template
.FuncMap
{"join": strings
.Join
}
137 guardians
= []string{"Gamora", "Groot", "Nebula", "Rocket", "Star-Lord"}
139 masterTmpl
, err
:= template
.New("master").Funcs(funcs
).Parse(master
)
143 overlayTmpl
, err
:= template
.Must(masterTmpl
.Clone()).Parse(overlay
)
147 if err
:= masterTmpl
.Execute(os
.Stdout
, guardians
); err
!= nil {
150 if err
:= overlayTmpl
.Execute(os
.Stdout
, guardians
); err
!= nil {
160 // Names: Gamora, Groot, Nebula, Rocket, Star-Lord