HTML Templates in Go
source link: https://www.devdungeon.com/content/html-templates-go
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
HTML Templates in Go
Submitted by NanoDano on Sat, 04/26/2014 - 19:51
Here is a quick example of how to use Go's html/template package to loop through a slice of structs and print out the contents. Note that in the templates {{.}} prints all the template variables, and . refers to the data passed.
type Person struct {
var Name string
var Age int
}
Simple struct definition for our Person
var persons []Person
// ... persons is filled with info somewhere ...
t, _ := template.ParseFiles("myTemplate.html")
t.Execute(response, persons)
Abbreviated code showing how we call the template and pass variables.
<html>
<body>
{{range .}}
<p>{{.Name}} {{.Age}}</p>
{{end}}
</body>
</html>
The {{range .}} iterates through . which is the data passed from template.Execute(). In this case it is a slice of Person structs. We are iterating through the slice and printing out the name and age associated with each struct.
Variable Maps
You can also use a map to send variables to the template.
// Create a variable map to send to the template
vars := map[string]interface{}{
"something": "some value",
"someNumber": 23,
}
// Pass the variables when executing the template
t.Execute(response, vars)
<p>
{{ .something }}<br />
{{ .someNumber }}
</p>
Advertisement
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK