func Example_autoescaping() { check := func(err error) { if err != nil { log.Fatal(err) } } t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) check(err) err = t.ExecuteTemplate(os.Stdout, "T", "<script>alert('you have been pwned')</script>") check(err) // Output: // Hello, <script>alert('you have been pwned')</script>! }
func Example() { const tpl = ` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>{{.Title}}</title> </head> <body> {{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}} </body> </html>` check := func(err error) { if err != nil { log.Fatal(err) } } t, err := template.New("webpage").Parse(tpl) data := struct { Title string Items []string }{ Title: "My page", Items: []string{ "My photos", "My blog", }, } err = t.Execute(os.Stdout, data) check(err) noItems := struct { Title string Items []string }{ Title: "My another page", Items: []string{}, } err = t.Execute(os.Stdout, noItems) check(err) // Output: // <!DOCTYPE html> // <html> // <head> // <meta charset="UTF-8"> // <title>My page</title> // </head> // <body> // <div>My photos</div><div>My blog</div> // </body> // </html> // <!DOCTYPE html> // <html> // <head> // <meta charset="UTF-8"> // <title>My another page</title> // </head> // <body> // <div><strong>no rows</strong></div> // </body> // </html> }