Skip to main content
This guide covers everything you need to know about writing templates in Mizu’s view system. We’ll explore Go’s template syntax, how data flows through your templates, and common patterns.

Template Basics

Mizu uses Go’s standard html/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:

Go Template Syntax

Outputting Values

Use .Data. to access your data:

Conditions

Use if to show content conditionally:

Comparison Operators

Go templates provide comparison functions:

Boolean Logic

Combine conditions with and, or, and not:

Loops

Use range 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 a range 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:
This is useful for keeping your HTML clean:

Layouts and Pages

Layout Structure

Layouts use {{.Content}} to include the rendered page:

Page Structure

Pages are simple - just write HTML with template expressions:
The page content is rendered first, then inserted into the layout’s {{.Content}}.

Common Patterns

Conditional Classes

Dynamic Attributes

Safe HTML Output

By default, Go templates escape HTML to prevent XSS attacks:
To output raw HTML (use only with trusted content!):

Empty/Nil Checks

Formatting Numbers and Dates

Use custom functions or printf:
For dates, either format in Go or use a custom function:
Or add a custom function:

Debugging Templates

Use printf 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 use template.HTML for content you trust completely.

5. Use Whitespace Trimming

Keep generated HTML clean: