Using the text/template package in Go

This week I'm working with the text/template package. As the page describes, "Package template implements data-driven templates for generating textual output."

In a nutshell, a template can be a string or file(s). A template includes Actions which are enclosed between {{ and }} brackets. Data is supplied, and the template is executed against it. The result of the text from evaluated actions are usually dependent on the data.

While this post aims to convey the usage of the package in simplest terms, templates can be very complex. Evaluated Actions can be conditional, templates can be nested, variables and functions can and do exist within Actions, the list goes on.

The Three Simple Steps

The example in this post makes use of one data structure and three methods in the text/template package.

  1. Create a variable of type text/template and name it.
var t template.Template = template.New("greeting")  
  1. Create a text template as a string, use the Parse function to supply the template that will be used.
t.Parse("Hello, {{.Name}}! Nice to meet you.")  
  1. Execute the template and provide the data structure that the template will be parsed against. The first argument the execute method is where output will be written to and is of type io.Writer.
type Person struct {  
        Name string 
}

var p = Person{"Corey"}  
t.Execute(os.Stdout, p)  

A working program for the example code above can be found here.

In practice

This example is slightly different but is seen more frequently than the example above. Here are the couple of lines in main that produce the output, "Hello there, Corey!"

var p = Person{"Corey"}  
var t = template.Must(template.New("greeting").Parse("Hello there, {{.Name}}!"))

err := t.Execute(os.Stdout, p)  
if err != nil { panic(err) }  

Notes

  • As you can see, the methods can be "chained"

  • template.Must is a wrapper for a function that returns both a pointer to a template.Template and an error. It panics if the error is non-nil.

  • The complete program can be found here.