Exploring the template Package
Explore how to work with Go's template package to create dynamic, data-driven text and HTML output. Understand template parsing, field substitution, control structures like if-else and range, and how to handle errors. This lesson helps you build flexible templates useful for web applications and other textual data generation.
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 ...