If you’re writing an application in Go, and you want templating functionality, there’s a built-in package template that’s available. This is a small guide about how to use it.
In my honest opinion, this templating system isn’t as elegant as others, but because it’s built into the language, it’s the one most people are going to use.
This guide is only compatible with Go0. It won’t work on Go1 because the API is slightly different, and the package has moved to “html/template”.
Here’s the most basic example:
package main
import "bytes"
import "template"
var tmpl = `
Hello! {{.text}}
`
func main() {
var buf bytes.Buffer
t,err := template.New("name").Parse(tmpl)
if err != nil {
println(err.String())
return
}
t.Execute(&buf, map[string]string{"text": "World"})
println(buf.String())
}
The name is useful when you’re calling a template from within another template.
Let’s explore some other features, like looping, and functions:
package main
import "bytes"
import "template"
var tmpl = `
<html>
<body>
<ul>
{{range .items}}
<li>{{.Text | html}} </li>
{{end}}
</ul>
</body>
</html>
`
type Item struct {
Text string
}
func main() {
var buf bytes.Buffer
t,err := template.New("name").Parse(tmpl)
if err != nil {
println(err.String())
return
}
t.Execute(&buf, map[string][]Item{"items": []Item{ {"Item1"}, {"Item2"}, {"<Item3>"}}})
println(buf.String())
}
This outputs:
<html>
<body>
<ul>
<li>Item1 </li>
<li>Item2 </li>
<li><Item3> </li>
</ul>
</body>
</html>
The html function escapes the content for use in an HTML file.
There’s a bunch of other features, including:
You can see more details about the template package here