Exploring the template Package

This lesson provides in-depth knowledge on functionalities and what support the template package offers.

Introduction

The documentation for the template package is available here. In the last lesson, we used templates to merge data from a (data) struct(ure)s with HTML-templates. This is very useful, indeed, for building web applications, but template techniques are more general than this. Data-driven templates can be made for generating textual output, and HTML is only a special case of this.

A template is executed by merging it with a data structure, in many cases a struct or a slice of structs. It rewrites a piece of text on the fly by substituting elements derived from data items passed to templ.Execute(). Only the exported data items are available for merging with the template. Actions can be data evaluations or control structures and are delimited by “{{” and “}}”. Data items may be values or pointers. The interface hides the indirection.

Field substitution

To include the content of a field within a template, enclose it within double curly braces and add a dot at the beginning, e.g. if Name is a field within a struct and its value needs to be substituted while merging, then include the text {{.Name}} in the template. This also works when Name is a key to a map. A new template is created with template.New, which takes the template name as a string parameter. As we already encountered previously, the Parse methods generate a template as an internal representation by parsing some template definition string. Use ParseFile when the parameter is the path to a file with the template definition. When there was a problem with the parsing, their second return parameter is an Error != nil. In the last step, the content of a data structure p is merged with the template through the Execute method, and written to its first argument, which is an io.Writer. Again, an error can be returned.

This is illustrated in the following program, where the output is written to the console through os.Stdout:

Get hands-on with 1200+ tech skills courses.