text/template package. A sibling package named html/template provides the same API but has additional security features.
Basic Templates
Create a template and parse its body from a string. Templates are a mix of static text and “actions” enclosed in{{...}}:
Using template.Must
Usetemplate.Must to panic in case Parse returns an error. This is especially useful for templates initialized in the global scope:
Executing Templates
Execute the template to generate text with specific values. The{{.}} action is replaced by the value passed to Execute:
Accessing Fields
Struct Fields
Access struct fields using{{.FieldName}}. Fields must be exported:
Map Fields
The same applies to maps, with no restriction on key name case:Conditional Execution
Useif/else for conditional execution. A value is considered false if it’s the default value of a type:
The
- in actions trims whitespace around the action.Range Loops
Loop through slices, arrays, maps, or channels. Inside the range block,{{.}} is set to the current item:
Template Actions
{{.}} - Current value
{{.}} - Current value
References the current context value
{{.Field}} - Field access
{{.Field}} - Field access
Accesses a field or map key
{{if .}} ... {{end}} - Conditional
{{if .}} ... {{end}} - Conditional
Conditionally renders content
{{range .}} ... {{end}} - Loop
{{range .}} ... {{end}} - Loop
Iterates over collections
{{- Action -}} - Trim whitespace
{{- Action -}} - Trim whitespace
Trims surrounding whitespace