Go Text Templates
Templates are a way to generate dynamic text (like HTML, emails, or reports) by combining a static string with dynamic data.
Basic Example
Go templates use double curly braces {{ }} to mark dynamic parts. Inside the template, {{.}} refers to the data passed in.
Control Structures
Templates support loops and conditions:
- Conditions:
{{if .Condition}} ... {{else}} ... {{end}} - Loops:
{{range .Slice}} ... {{.}} ... {{end}}
Accessing Fields
If you pass a struct to a template, you can access its fields using a dot: {{.FieldName}}.
Why use Templates?
- Separation of Concerns: Keep your text/HTML separate from your Go code.
- Reusable Layouts: Define a "base" layout and swap the content inside.
- Security: If you use
html/template(instead oftext/template), Go will automatically escape special characters to prevent XSS attacks. factory methods.