Introduction to Go Templates

Using templates in Go is a great way to produce content in a dynamic way. Go makes it possible to prepare content for display as pure text (by using the text/template
package or as HTML with proper encoding (by using the html/template
package). Both of these packages can be found in the Go standard library, and they are incredibly useful in presenting data neatly. In this blog post, I will introduce templates in Go by going over the steps to produce one line of formatted content from a template string.
The first step is to create a Go file called main.go
that imports the necessary packages and defines the main
function.
package main
import (
"os"
"text/template"
)
func main() {
// insert code here
}
For this tutorial, I will be using a struct called Person
, which can be defined as so:
type Person struct {
Name string
Age int
}
In main.go
, we first initialize a new template called demo
, and we then parse the template string to ensure there are no syntax errors. We use the panic
function to handle errors quickly. We then execute the template using the Execute
function which takes in two arguments: the first argument is to specify where you want the final report to be printed (this could be another file or the terminal). For this demo, the final report will be printed to the terminal (os.Stdout
). The second argument specifies the data that is sent to the template string. In this demo, one instance of the struct Person
is passed into the template string. Code for this step is shown below:
person := Person{"Alex", 32}
tmpl, err := template.New("demo").Parse("{{.Name}} is {{.Age}} years old")
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, person)
if err != nil {
panic(err)
}
In the template string, both the Name
and Age
attributes of the Person
object are accessed by prepending a .
to the attribute name. The .
here represents the Person
object. Main.go
now looks like this:
package main
import (
"os"
"text/template"
)
type Person struct {
Name string
Age int
}
func main() {
person := Person{"Alex", 32}
tmpl, err := template.New("demo").Parse("{{.Name}} is {{.Age}} years old")
if err != nil {
panic(err)
}
err = tmpl.Execute(os.Stdout, person)
if err != nil {
panic(err)
}
}
After running go run main.go
, you will get the following output in the terminal:
Alex is 32 years old
Subscribe to my newsletter
Read articles from Alissa Lozhkin directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Alissa Lozhkin
Alissa Lozhkin
My name is Alissa and I am a fourth-year computer science and math student at the University of Toronto! I am very interested in computer science and software development, and I love learning about new technologies! Get in touch with me on LinkedIn: https://www.linkedin.com/in/alissa-lozhkin