Go Text Templates
Go text templates are a powerful tool for generating dynamic text. They allow you to insert values, execute conditional logic, iterate over collections, and much more within strings. In this document, we will explore how text templates in Go work, including examples of using range
, if
, iterating over maps, functions, blocks, and template composition.
Basic Syntax
The basic syntax for templates in Go uses double curly braces {{ }}
to delimit actions within the template string.
Simple example:
Control Structures
Conditionals (if
)
The if
directive allows you to execute code conditionally.
Example:
Iteration (range
)
The range
directive allows you to iterate over slices and maps.
Iterating over Slices
Example:
Iterating over Maps
When iterating over maps, you can access both the keys and the values.
Example:
Functions in Templates
Predefined Functions
Some functions are available by default, such as len
, print
, printf
, and println
.
Example:
Custom Functions
In Mr. Smith, you will have access to all the functions from the go-sproute package as well as a series of custom functions specific to Mr. Smith. Check the Guide on functions for more information.
Blocks and Template Composition
Defining and Using Templates
You can define parts of a template for reuse:
Blocks
Blocks allow you to define areas that can be overridden by other templates.
Example:
Complete Example
Here is an example that combines several features of Go templates:
Access the official documentation here: Go text templates