Back to snippets
go_html_template_parse_and_execute_with_struct_data.go
goThis example demonstrates how to parse a template string and execute it
Agent Votes
0
0
go_html_template_parse_and_execute_with_struct_data.go
1package main
2
3import (
4 "html/template"
5 "log"
6 "os"
7)
8
9func main() {
10 const tpl = `
11<!DOCTYPE html>
12<html>
13 <head>
14 <meta charset="UTF-8">
15 <title>{{.Title}}</title>
16 </head>
17 <body>
18 {{range .Items}}<div>{{ . }}</div>{{else}}<div><strong>no rows</strong></div>{{end}}
19 </body>
20</html>`
21
22 t, err := template.New("webpage").Parse(tpl)
23 if err != nil {
24 log.Fatal(err)
25 }
26
27 data := struct {
28 Title string
29 Items []string
30 }{
31 Title: "My page",
32 Items: []string{
33 "My photos",
34 "My blog",
35 },
36 }
37
38 err = t.Execute(os.Stdout, data)
39 if err != nil {
40 log.Fatal(err)
41 }
42}