Templates
- Introduction
- Displaying data
- Expressions
- Control structures
- Layouts
- Components with macros
- dust-framework's helpers
- Filters
- Functions
- Whitespace control
- Debugging templates
Introduction
dust-framework's views use Jinja template syntax, rendered by MiniJinja. Templates give you expressions, conditionals, loops, reusable layouts, filters, and macro components so your HTML stays clean and expressive.
[!NOTE] To learn where view files live and how handlers pass data to them, check out the views guide. For the full template language reference, check out MiniJinja's syntax documentation.
Displaying data
To output data passed to a view, wrap the variable name in double curly braces. For example, if a handler returns view("welcome", data! { name => "Samantha" }), your template may display name like this:
<h1>Hello, {{ name }}</h1>Any expression works inside curly braces, including values transformed by a filter:
Hello, {{ name|upper }}. You have {{ orders|length }} orders.Every view also has access to app_name and app_url, populated from APP_NAME and APP_URL. If your handler passes its own app_name or app_url value, that value overrides the default.
Escaping
Every value output with {{ ... }} is HTML-escaped automatically, so user input containing <script> tags renders as plain text rather than executing. None outputs nothing, and booleans output as true or false (for example, aria-expanded="{{ open }}").
To output trusted HTML without escaping it, apply the safe filter:
<article>{{ post.body_html|safe }}</article>[!WARNING] Only use
safeon HTML you trust, since unescaped user input can inject scripts into your page. When your handler builds trusted HTML, prefer passing it withwith_html.
Lists and maps output in a debug representation such as ["a", "b"]. To format a list as readable text, join it with the join filter: {{ tags|join(", ") }}.
Missing data
Referencing or looping over a variable that wasn't passed to the view fails with an error rather than rendering an empty string. To check whether a variable was provided, use is defined:
{% if user is defined %} Hello, {{ user.name }}{% else %} Hello, guest{% endif %}Because is defined treats None as defined, write {% if user is defined and user is not none %} when a value might be either missing or None. A plain {% if user %} works too, though it also evaluates to false for empty strings, zero, and empty lists.
To provide a fallback value for a missing variable, use the default filter:
<title>{{ title|default(app_name) }}</title>Passing data to scripts
Sometimes client-side JavaScript needs data from your handler, such as data points for a chart. Use the js filter to serialize values safely inside <script> tags and quoted HTML attributes (such as Alpine's x-data). Always quote the attribute:
<div x-data="{ points: {{ points|js }} }"></div><script> const points = {{ points|js }};</script>[!WARNING] Never use
tojsoninside a double-quoted HTML attribute. Becausetojsondoesn't escape double quotes, user data could break out of the attribute. Usejs, or wraptojsonin single quotes such asdata-points='{{ points|tojson }}'.
Raw blocks
Some frontend libraries also use {{ ... }} syntax. To prevent MiniJinja from parsing that markup, wrap it in a raw block so it is output untouched:
{% raw %} <div>Hello, {{ name }}.</div>{% endraw %}Comments
Template comments are stripped out and never appear in the rendered HTML:
{# This comment won't be in the page. #}Expressions
Values, fields, and items
Strings accept single or double quotes, and lists and maps use JSON-like syntax:
{{ "Hello" }} {{ 'world' }} {{ 42 }} {{ 3.14 }} {{ true }} {{ none }}{% set colors = ["red", "green"] %}{% set sizes = {"small": 12, "large": 18} %}Access fields with dot notation, or bracket notation when a key isn't a valid identifier. Access list items by index (negative indexes count from the end) and slice lists with ranges:
{{ user.name }}{{ user["first-name"] }}{{ orders[0].number }}{{ orders[-1].number }}{{ items[1:3]|join(", ") }}Operators
| Operators | Meaning |
|---|---|
+ - * / % |
Arithmetic: 10 / 4 is 2.5. |
// ** |
Floor division and exponentiation: 7 // 2 is 3, 2 ** 3 is 8. |
== != < <= > >= |
Comparison. |
and or not |
Boolean logic. |
in |
Membership in a list, string, or map: "admin" in roles. |
~ |
String concatenation: "Order #" ~ order.id. |
x if condition else y |
Inline conditional: {{ "Active" if user.active else "Inactive" }}. |
x is test |
A value test, such as count is odd. |
x|filter |
A filter, such as name|upper. |
Control structures
If statements
Use if, elif, and else blocks to render markup conditionally:
{% if orders|length == 1 %} You have one order.{% elif orders %} You have {{ orders|length }} orders.{% else %} You haven't ordered anything yet.{% endif %}Use not to negate a condition, such as {% if not user.verified %}.
Checking values
To test a value in a condition, such as checking whether a number is odd, write is (or is not) followed by a test name:
{% if user is defined %} ... {% endif %}{% if loop.index is divisibleby(3) %}<hr>{% endif %}{% if name is not none %} ... {% endif %}Check out MiniJinja's test reference for the full list. These are the most common tests:
| Test | Passes when the value |
|---|---|
defined, undefined |
Was or wasn't passed to the view. |
none |
Is None. |
true, false, boolean |
Is true, false, or either boolean. |
odd, even, divisibleby(n) |
Is odd, even, or a multiple of n. |
number, integer, float, string |
Has that type. |
sequence, mapping, iterable |
Is a list, map, or any iterable collection. |
startingwith(text), endingwith(text) |
Is a string starting or ending with the given text. |
in(list) |
Appears in the list (equivalent to the in operator). |
eq, ne, lt, le, gt, ge |
Compares like ==, !=, <, <=, >, and >=, useful inside selectattr. |
safe |
Is already marked as trusted HTML. |
Loops
Use for to iterate over a list. An optional else branch renders when the list is empty:
<ul> {% for user in users %} <li>{{ user.name }}</li> {% else %} <li>No users.</li> {% endfor %}</ul>To iterate over a map's keys and values together, apply the items filter:
{% for name, score in scores|items %} {{ name }}: {{ score }}{% endfor %}You may filter a loop inline with if, skip an iteration with {% continue %}, or stop early with {% break %}:
{% for user in users if user.active %} {% if loop.index > 10 %}{% break %}{% endif %} <li>{{ user.name }}</li>{% endfor %}The loop variable
Inside any for loop, the loop variable exposes information about the current iteration:
| Property | Description |
|---|---|
loop.index |
The current iteration, starting at 1. |
loop.index0 |
The current index, starting at 0. |
loop.revindex, loop.revindex0 |
Remaining iterations, counting down to 1 or 0. |
loop.first, loop.last |
Whether this is the first or last iteration. |
loop.length |
Total number of items in the loop. |
loop.previtem, loop.nextitem |
The previous and next items (undefined at the boundaries). |
loop.cycle(..) |
Cycles through its arguments, such as loop.cycle("odd", "even"). |
loop.changed(..) |
Whether its argument changed since the previous iteration, useful for group headings. |
Setting variables
Use set to assign a local variable inside a template:
{% set total = orders|map(attribute="total")|sum %}The block form captures rendered markup into a variable:
{% set greeting %}Welcome back, {{ user.name }}!{% endset %}Use with to scope variables to a single block:
{% with heading = "Users", count = users|length %} <h2>{{ heading }} ({{ count }})</h2>{% endwith %}Variables assigned inside a loop don't persist across iterations. To accumulate a value across loop iterations, store it on a namespace:
{% set totals = namespace(paid=0) %}{% for order in orders if order.paid %} {% set totals.paid = totals.paid + order.total %}{% endfor %}Paid: {{ totals.paid }}Layouts
Most pages in an application share the same outer structure, such as a header, navigation bar, and footer. Define that shared structure once in a layout template and mark replaceable sections with block tags:
<!-- resources/views/layouts/app.html --><!DOCTYPE html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>{% block title %}{{ app_name }}{% endblock %}</title> <link rel="stylesheet" href="/vendor/io-ui/paz.css"></head><body> {% include "partials.nav" %} <main class="container"> {% block content %}{% endblock %} </main> <aside class="sidebar"> {% block sidebar %}{% endblock %} </aside> <script type="module" src="/vendor/io-ui/paz.js"></script></body></html>Child views extend the layout with extends and override the blocks they need:
<!-- resources/views/users/index.html -->{% extends "layouts.app" %}{% block title %}Users{% endblock %}{% block content %} <ul> {% for user in users %} <li>{{ user.name }}</li> {% endfor %} </ul>{% endblock %}Any block a child view doesn't override keeps the layout's default content (such as sidebar above). To keep the layout's content and append to it, call {{ super() }} inside the child block:
{% block sidebar %} {{ super() }} <p>Filter users by role.</p>{% endblock %}Layouts may extend other layouts, and any named block may be rendered on its own as a fragment.
Including views
To embed one template inside another, use include. The included template inherits all variables from the current template:
{% include "partials.nav" %}To pass additional scoped variables to the included view, wrap it in with:
{% with heading = "Users" %} {% include "partials.header" %}{% endwith %}To skip an include silently if the file doesn't exist, add ignore missing, as in {% include "partials.promo" ignore missing %}.
Components with macros
When you reuse small UI elements such as buttons or cards across many pages, define them as macros. Macros work like functions that return markup, accept positional or keyword arguments with optional defaults, and can live in a shared template:
<!-- resources/views/components.html -->{% macro button(label, type="button", variant="primary") %} <button type="{{ type }}" class="button button-{{ variant }}">{{ label }}</button>{% endmacro %}{% macro card(title) %} <section class="card"> <h2>{{ title }}</h2> {{ caller() }} </section>{% endmacro %}Import the macros in any template that needs them:
{% import "components" as ui %}{{ ui.button("Save", type="submit") }}{% call ui.card("Orders") %} <p>{{ orders|length }} this week</p>{% endcall %}A call block passes inner markup to the macro, which renders it where {{ caller() }} appears. To import specific macros by name without a namespace, use {% from "components" import button, card %}.
Component attributes
Reusable components often need to accept arbitrary HTML attributes such as extra classes or data-* attributes. Accept them as an attrs={} map and render them with attributes(..).
Calling merge sets default attributes for the component: class and style values are merged with the caller's values, while any other caller-supplied attribute overrides its default:
<!-- resources/views/components/button.html -->{% macro button(variant="primary", attrs={}) -%} <button {{ attributes(attrs).merge( type="button", class=[ "btn", {"btn-primary": variant == "primary", "btn-ghost": variant == "ghost"} ] ) }}> {{ caller() }} </button>{%- endmacro %}{% from "components.button" import button %}{% call button(variant="ghost", attrs={ "class": "mr-2", "type": "submit", "data-order": order.id, "disabled": not order.can_ship,}) %} Ship order{% endcall %}<button type="submit" class="btn btn-ghost mr-2" data-order="42" disabled> Ship order</button>attributes escapes strings and numbers automatically. Boolean true renders a bare attribute such as disabled, while false, none, or missing values omit the attribute. class accepts lists and conditional maps such as ["btn", {"active": is_active}].
For default attributes whose names aren't valid identifiers (such as aria-label), pass a map as the first argument to merge: .merge({"aria-label": label}, class="icon"). Attributes also provide these methods:
| Method | Description |
|---|---|
only(..), except(..) |
Keeps only the named attributes, or excludes them: attributes(attrs).except("id"). |
has(name) |
Returns whether the attribute is present. |
get(name) |
Returns the attribute's value, or none. |
A component wrapping another component may merge its own defaults and forward the attributes:
{% macro icon_button(icon, attrs={}) -%} {% call button(attrs=attributes(attrs).merge({"aria-label": icon}, class="icon-button")) %} <i class="icon-{{ icon }}"></i> {% endcall %}{%- endmacro %}dust-framework's helpers
Every template includes built-in dust-framework helper functions for generating URLs, linking package assets, rendering head metadata, protecting forms, and reading session data. They are registered by the framework, so you call them without an import.
Assets
Your own assets and the io/ui files are served from public/, so a template links them with a plain path:
<link rel="stylesheet" href="/vendor/io-ui/paz.css"><script type="module" src="/vendor/io-ui/paz.js"></script><img src="/images/logo.svg" alt="Example">For an asset shipped by a package, call vendor_asset instead, so the URL includes the namespace and the content hash:
<link rel="stylesheet" href="{{ vendor_asset("inspire", "inspire.css") }}">url("/about") builds an absolute URL for one of your own paths, which is useful in an email or a canonical link. route(...) builds a URL from a route's handler, as URLs describes.
Content Security Policy nonces
A strict Content-Security-Policy header blocks inline scripts and external scripts that do not carry a per-request nonce. To generate a nonce for each request, write a middleware that creates a random token, registers it with view::use_csp_nonce, and allows the same nonce in the response's Content-Security-Policy header:
use dust::http::{Next, Request, Response, middleware};use dust::view;#[middleware]pub async fn csp_headers(request: Request, next: Next) -> Response { let nonce = dust::str::random(32); view::use_csp_nonce(&nonce); let response = next.run(request).await; response.with_header( "content-security-policy", format!("script-src 'nonce-{nonce}' 'strict-dynamic'; style-src 'nonce-{nonce}'"), )}<script nonce="{{ csp_nonce() }}"> // Runs only when the nonce matches the response header...</script>In a handler or middleware, view::csp_nonce() returns the same nonce as an Option<String>.
Subresource integrity
Subresource integrity (SRI) lets a browser refuse a script or stylesheet whose contents don't match a hash you published with the page. Generate the hash from the built file, then put it on the tag:
openssl dgst -sha384 -binary public/js/app.js | openssl base64 -A<script src="/js/app.js" integrity="sha384-<the base64 hash>" crossorigin="anonymous"></script>crossorigin="anonymous" is required when the file comes from another origin, and the server must send Access-Control-Allow-Origin for it. Regenerate the hash whenever the file changes, which is why this is usually part of the asset build rather than something you write by hand. The vendored io/ui files change on ui:update, so if you add SRI to them, update the hash in the layout at the same time.
URLs
The url function generates an absolute URL for a path in your application:
<a href="{{ url("/about") }}">About us</a>The route function generates a URL for one of your routes by naming its handler's path as printed by route:list. The trailing segments are enough, such as posts::show for app::http::handlers::posts::show:
<a href="{{ route("posts::show", post) }}">{{ post.title }}</a>Positional arguments fill route {placeholders} in order, matching dust::url::route. Passing a map or model fills the placeholder with its id, or with the column named in the placeholder (such as slug for {post:slug}). Keyword arguments fill placeholders by name or append to the query string:
{{ route("posts::index") }} {# http://localhost/posts #}{{ route("posts::show", post) }} {# http://localhost/posts/1 #}{{ route("comments::show", post, comment) }} {# http://localhost/posts/1/comments/2 #}{{ route("posts::index", page=2) }} {# http://localhost/posts?page=2 #}If more than one handler ends with the path you provided, rendering fails with an error listing the matches so you can include more of the module path.
To link to an asset shipped by a package, call vendor_asset, such as {{ vendor_asset("inspire", "inspire.css") }}.
[!WARNING] Because template strings aren't checked by the Rust compiler, renaming a handler or module breaks any template that names it. Write HTTP tests that render your views to catch broken route names early.
Head metadata
The head function renders the page's title, description, canonical link, and other head metadata:
<head> <meta charset="utf-8"> {{ head() }}</head>Handlers customize a page's metadata with head::merge before returning the view.
Forms and CSRF
Forms posting to routes in the web group must include the session's CSRF token. Call csrf_field() inside the form to render the hidden _token input:
<form method="POST" action="/profile"> {{ csrf_field() }} <!-- ... --></form>A GET form doesn't change state, so it doesn't need the token. Give every form an explicit action and method: a form without an action posts to the current URL, which is rarely what you want after a validation redirect.
Because HTML forms only support GET and POST, include a hidden _method field for PUT, PATCH, and DELETE routes using form method spoofing:
<form method="POST" action="{{ route("posts::destroy", post) }}"> {{ csrf_field() }} <input type="hidden" name="_method" value="DELETE"> <button type="submit">Delete post</button></form>Validation errors and old input
When a form fails validation, dust-framework redirects back and makes the validation errors and old input available to the view. Call error(..) to display a field's first error message (it returns nothing when the field has no errors, so it works in if checks too), and call old(..) to repopulate what the user typed (falling back to its second argument):
<input name="email" value="{{ old("email", user.email) }}" class="{{ "invalid" if error("email") }}">{% if error("email") %} <p class="error">{{ error("email") }}</p>{% endif %}Use "dot" notation for nested fields, such as error("address.city") and old("address.city"). old never returns password fields.
Every view also receives an errors map containing all messages per field. Use it for an error summary ({% if errors %}) or to list every error on a field ({% for message in errors.email %}). On a page with several forms, pass the form name to read its errors: error("email", form="login").
Session data
The session function reads a key from the session, such as a flashed status banner, returning none if the key isn't present:
{% if session("status") %} <div class="alert">{{ session("status") }}</div>{% endif %}csrf_token(), csrf_field(), and session(..) require a session and work only in views rendered for routes in the web group.
Filters
Filters transform values using the | operator. They accept optional arguments and chain from left to right:
{{ name|title }}{{ tags|join(", ") }}{{ users|selectattr("active")|map(attribute="email")|join(", ") }}Available filters
These are the filters you'll reach for most often. Check out MiniJinja's filter reference for the complete list.
| Strings | Description |
|---|---|
upper, lower |
Converts text to uppercase or lowercase. |
title, capitalize |
Capitalizes each word, or only the first word. |
trim |
Strips whitespace from both ends. |
replace(from, to) |
Replaces occurrences of text. |
split(separator), lines |
Splits a string into a list by separator or by lines. |
format(..) |
Fills %s placeholders: "%s of %s"|format(page, pages). |
urlencode |
Percent-encodes text for a URL query string. |
| Lists | Description |
|---|---|
length, count |
Returns the number of items (also works on strings and maps). |
join(separator) |
Joins items into a single string. |
first, last |
Returns the first or last item. |
min, max, sum |
Returns the smallest, largest, or total value. |
sort, reverse, unique |
Sorts, reverses, or deduplicates items (sort(attribute="name") sorts by field). |
map(attribute=..) |
Extracts a field from each item (users|map(attribute="email")), or applies a filter (map("upper")). |
select(test), reject(test) |
Keeps or drops items matching a test: numbers|select("odd"). |
selectattr(field), rejectattr(field) |
Keeps or drops items whose field is truthy or passes a test: users|selectattr("role", "eq", "admin"). |
groupby(field) |
Groups items by field into objects with grouper and list. |
batch(size), slice(count) |
Splits a list into fixed-size rows or a given number of columns. |
| Numbers | Description |
|---|---|
round(precision) |
Rounds to a number of decimal places: price|round(2). |
abs |
Returns the absolute value. |
int, float |
Converts to an integer or floating-point number. |
| Dates | Description |
|---|---|
date(format) |
Formats a date in UTC using strftime syntax: created_at|date renders October 5, 2026, and created_at|date("%b %-d, %H:%M") renders Oct 5, 14:30. Pass tz="America/Chicago" for another timezone. |
for_humans |
Formats a relative time such as 3 minutes ago or in 2 hours, measured from dust::now(). |
compact_for_humans |
Abbreviates the unit in a relative time: {{ post.created_at|compact_for_humans }} renders 3m ago instead of 3 minutes ago. |
These filters accept ISO date and timestamp strings serialized by your models, such as 2026-10-05T14:30:00Z and 2026-10-05.
| Maps | Description |
|---|---|
items |
Returns key-value pairs for iterating in a loop. |
dictsort |
Returns key-value pairs sorted by key. |
| Other | Description |
|---|---|
default(value), d(value) |
Returns a fallback when a variable is undefined. |
safe |
Marks a value as trusted HTML so it isn't escaped. |
escape, e |
Escapes a value immediately. |
js |
Encodes a value safely for scripts and quoted attributes. |
tojson |
Serializes a value as JSON. |
pprint |
Pretty-prints a value for debugging. |
Custom filters and functions
When the built-in filters don't cover what you need, register your own inside with_views in src/app.rs using views.minijinja(...). Each filter or function is a regular Rust function or closure:
use dust::prelude::*;Application::configure() .with_views(|views, _| { views.minijinja(|environment| { environment.add_filter("money", |cents: i64| { format!("${}.{:02}", cents / 100, cents % 100) }); environment.add_function("year", || dust::now().year()); }); }){{ order.total|money }} © {{ year() }}A package may register custom filters and functions by calling app.views().minijinja(...) inside its service provider's register method. dust-framework re-exports MiniJinja at dust::view::minijinja for types such as Value, and the minijinja-contrib crate provides additional filters like truncate and wordcount.
Functions
In addition to dust-framework's helpers and feature(..) for feature flags, MiniJinja provides these built-in functions:
| Function | Description |
|---|---|
range(stop), range(start, stop, step) |
Generates a sequence of numbers: {% for i in range(1, 6) %}. |
dict(..) |
Builds a map from keyword arguments: dict(size="large", color="red"). |
namespace(..) |
Creates a mutable object for updating values inside loops. |
debug() |
Outputs all variables in scope for debugging templates. |
Whitespace control
Adding - inside a tag's delimiter strips surrounding whitespace (including newlines) on that side:
<ul> {%- for item in items %} <li>{{ item }}</li> {%- endfor %}</ul>Debugging templates
A template that fails to render, such as one referencing a misspelled variable, produces a server error. In debug mode, the error page highlights the template's file, line, and surrounding source.
To inspect every variable currently available in a template, output debug():
<pre>{{ debug() }}</pre>