HTML Templates in Go

Advertisement

Advertisement

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

Advertisement