Template Basics
Mizu uses Go’s standardhtml/template package. Templates are HTML files with special markers ({{ and }}) for dynamic content.
Accessing Data
In Mizu templates, your data is wrapped in a structure. Access your data using.Data:
The Template Data Structure
Templates receive this structure:| Field | Description | Available In |
|---|---|---|
.Page.Name | Template name (e.g., “home”) | Pages and Layouts |
.Page.Layout | Layout name (e.g., “default”) | Pages and Layouts |
.Data | Your data from the handler | Pages and Layouts |
.Content | Rendered page content | Layouts only |
Go Template Syntax
Outputting Values
Use.Data. to access your data:
Conditions
Useif to show content conditionally:
Comparison Operators
Go templates provide comparison functions:| Function | Description | Example |
|---|---|---|
eq | Equal | {{if eq .Data.Status "active"}} |
ne | Not equal | {{if ne .Data.Count 0}} |
lt | Less than | {{if lt .Data.Price 100}} |
le | Less than or equal | {{if le .Data.Stock 5}} |
gt | Greater than | {{if gt .Data.Price 100}} |
ge | Greater than or equal | {{if ge .Data.Age 18}} |
Boolean Logic
Combine conditions withand, or, and not:
Loops
Userange to iterate over slices, arrays, or maps:
Looping Over Structs
When ranging over a slice of structs:Looping Over Maps
Variables
Assign values to variables with:=:
The Root Context ($)
Inside arange loop, . refers to the current item. Use $ to access the root context:
$ always refers to the original data passed to the template.
Pipelines
Chain operations with|:
Comments
Template comments are stripped from output:Whitespace Control
Use- to trim whitespace:
Layouts and Pages
Layout Structure
Layouts use{{.Content}} to include the rendered page:
Page Structure
Pages are simple - just write HTML with template expressions:{{.Content}}.
Common Patterns
Conditional Classes
Dynamic Attributes
Safe HTML Output
By default, Go templates escape HTML to prevent XSS attacks:Empty/Nil Checks
Building Links
Formatting Numbers and Dates
Use custom functions orprintf:
Debugging Templates
Print Values
Useprintf with %#v to see the Go syntax representation:
Check Types
Enable Development Mode
For detailed error messages with line numbers:Best Practices
1. Keep Templates Simple
Put complex logic in Go handlers, not templates:2. Use Meaningful Variable Names
3. Document Expected Data
Add comments at the top of templates:4. Escape User Input
Always let Go’s default escaping protect against XSS. Only usetemplate.HTML for content you trust completely.