dust

Views

Introduction

Returning entire HTML documents as strings from your route handlers isn't practical. Views separate your HTML into dedicated files under resources/views, leaving your handlers focused on loading the data a page needs.

dust-framework's views are templates written in Jinja syntax, and every value they render is HTML-escaped automatically. For example, a simple greeting view in resources/views/greeting.html looks like this:

html
<!-- resources/views/greeting.html --><html>    <body>        <h1>Hello, {{ name }}</h1>    </body></html>

[!NOTE] Looking for details on template syntax such as loops, layouts, filters, and components? Check out the templates guide.

Creating and rendering views

To create a view, place a file with the .html extension in resources/views, then return it from a handler with the view function:

rust
use dust::prelude::*;use dust::view::View;pub async fn show() -> View {    view("greeting", data! { name => "James" })}

The first argument is the view's name (its path inside resources/views without the .html extension), and the second argument is the data to pass to the template. For a view that needs no data, pass () as in view("about", ()).

If a view doesn't exist or references a variable that wasn't passed to it, dust-framework responds with a 500 error. In debug mode, the error page points directly to the template's file and line.

Nested view directories

Views may be organized into subdirectories under resources/views. Use "dot" notation to reference nested views, so resources/views/admin/profile.html is rendered as admin.profile:

rust
view("admin.profile", data! { name => "Taylor" })

Templates reference other nested views using the same dot notation, such as {% extends "layouts.app" %}.

Determining if a view exists

To check whether a view exists before rendering it, call dust::view::exists. It checks both your application's views and views registered by packages:

rust
if dust::view::exists("admin.profile") {    // ...}

Rendering a view to a string

Sometimes you need a view's rendered HTML as a string rather than an HTTP response, such as when saving a generated report to file storage. Call render() to produce an Html value, then convert it to a String with into_string():

rust
use dust::prelude::*;use dust::storage;pub async fn store() -> dust::Result<Redirect> {    let html = view("reports.summary", data! { month => "October", orders => 42 }).render()?;    storage::put("reports/october.html", html.into_string()).await?;    Ok(Redirect::to("/reports"))}

When a view fails

A view can fail before it renders a single byte, and each failure points at a different fix:

Failure Cause Fix
The view doesn't exist The name doesn't match a file under resources/views, or the extension isn't registered. Check the dot path and the file name; dust::view::exists answers the same question in code.
A variable is undefined The handler didn't pass it, and it isn't shared. Add it to data!, a shared value, or a {% if x is defined %} guard.
A filter or function is unknown The name is misspelled or the package that adds it isn't registered. Check the filter table in the templates guide; register custom ones with views.minijinja.
The page renders but a section is empty The block has the wrong name, or the child view never overrides it. Compare the block names in the layout and the child.
The error page points at the template Debug mode shows the file and line. Fix the template, not the handler.

In debug mode, the error page names the template file and line. Outside debug mode, the user gets a generic 500 and the details go to your logs, so reproduce the failure locally before deploying a template change.

Passing data to views

Use the data! macro to pass variables to a view. List a local variable to pass it under its own name, or use name => value to give it a custom key. Each entry becomes a template variable, so the view below can loop over users and render {{ title }}:

rust
use dust::prelude::*;use dust::view::View;use crate::models::User;pub async fn index() -> dust::Result<View> {    let users = User::all().await?;    Ok(view("users.index", data! { users, title => "Users" }))}

You may also pass any struct that derives Serialize, and each struct field becomes a variable in the template. Defining a struct is especially helpful when multiple handlers render the same view, because the compiler verifies that every handler supplies all required fields:

rust
#[derive(Serialize)]struct UserList {    title: &'static str,    users: Vec<User>,}pub async fn index() -> dust::Result<View> {    let users = User::all().await?;    Ok(view("users.index", UserList { title: "Users", users }))}

Sharing data with all views

When every view in your application needs the same value, such as your support email address, share it globally inside with_views in src/app.rs:

rust
use dust::foundation::ApplicationBuilder;use dust::prelude::*;pub fn configure() -> ApplicationBuilder {    Application::configure()        // ...        .with_views(|views, config| {            views.share("support_email", config.mail.from.email());        })}

A package may share data with all views by calling app.views().share(...) inside its service provider's register method.

For data that varies per request, such as the logged-in user, call dust::view::share inside a middleware. Only views rendered during that request receive the shared value:

rust
use dust::http::{Next, Request, Response, middleware};use crate::models::User;#[middleware]pub async fn share_user(request: Request, next: Next) -> dust::Result<Response> {    let user: Option<User> = request.user().await?;    dust::view::share("user", user);    Ok(next.run(request).await)}

When the same variable name is defined in more than one place, dust-framework uses the data passed directly to view(...) first, then data shared for the current request, and finally data shared globally with all views.

Source Scope Wins when a name repeats
view("name", data! { ... }) One render First
dust::view::share in a middleware The request Second
views.share in src/app.rs The application Third

A view that needs a value in every branch of its template is easier to reason about when the handler passes it explicitly. Reserve global sharing for values such as the support email that truly never change per request.

Passing markup

Because templates escape every value they output, raw HTML built in your handler would appear as literal text. When you want to render trusted HTML markup, such as a post body converted from Markdown with the markdown crate, wrap it in Html::raw and pass it with with_html:

rust
use dust::prelude::*;use dust::view::{Html, View};use crate::models::Post;pub async fn show(post: Post) -> View {    let body = Html::raw(markdown::to_html(&post.body));    view("posts.show", data! { post }).with_html("body", body)}

markdown::to_html escapes any raw HTML inside the Markdown input, so this example is safe even for user-authored posts.

[!WARNING] Never pass untrusted user input directly to Html::raw without escaping or sanitizing it first. Unescaped HTML is rendered as written and can allow cross-site scripting (XSS) attacks.

Rendering fragments

Sometimes a request only needs one section of a page, such as updating a search results list as the user types. Instead of duplicating markup in a second template, render a single named block from the existing view. For example, this view wraps its list in a results block:

html
<!-- resources/views/users/index.html -->{% extends "layouts.app" %}{% block content %}    <form method="GET" action="/users">        <input type="search" name="q">        <button type="submit">Search</button>    </form>    <ul id="results">        {% block results %}            {% for user in users %}                <li>{{ user.name }}</li>            {% endfor %}        {% endblock %}    </ul>{% endblock %}

Call fragment on the View to render only the results block:

rust
use dust::prelude::*;use dust::view::View;use crate::models::User;#[dust::query]pub struct Search {    #[default]    q: String,    fragment: Option<String>,}pub async fn results(Query(search): Query<Search>) -> dust::Result<View> {    let users = User::query().filter(User::name.contains(&search.q)).get().await?;    Ok(view("users.index", data! { users }).fragment("results"))}

If a single handler serves both full page loads and partial updates, call fragment_if to render only the block when a condition is true:

rust
pub async fn index(Query(search): Query<Search>) -> dust::Result<View> {    let users = User::query().filter(User::name.contains(&search.q)).get().await?;    let partial = search.fragment.as_deref() == Some("results");    Ok(view("users.index", data! { users }).fragment_if(partial, "results"))}

Now /users?q=Alice renders the full page, while /users?q=Alice&fragment=results renders only the results block for your JavaScript to swap into #results.

Reloading and deploying views

In debug mode, dust-framework reloads templates from disk on every render so your edits appear immediately when you refresh the browser. Outside debug mode, dust-framework compiles each view the first time it is rendered and caches it until the application restarts.

Because your application reads views from resources/views at runtime rather than baking them into the binary, include resources/views alongside your compiled binary under your application's base path when deploying to your own servers. If you deploy to DUST Cloud, this is handled for you automatically.

Views from packages

A package that provides pages or emails ships its own templates by embedding them in the binary with dust::embed!, then registering them under a namespace via app.views() in its service provider:

rust
use dust::container::Registrar;use dust::foundation::ServiceProvider;pub struct BillingServiceProvider;impl ServiceProvider for BillingServiceProvider {    fn register(&self, app: &mut Registrar) {        app.views().namespace("billing", dust::embed!("resources/views"));    }}

Package views are referenced with a namespace:: prefix, so billing::invoice resolves to the package's resources/views/invoice.html. To override a package's view in your application, place your customized template at resources/views/vendor/billing/invoice.html, which dust-framework checks before falling back to the package's embedded copy.

namespace also accepts a directory path if you want to keep some of your application's own views outside resources/views, such as views.namespace("mail", "resources/mail") inside with_views.

Other template engines

dust-framework renders .html templates with MiniJinja. To support another file extension such as .md, implement dust::view::Engine and register it in a service provider:

rust
use dust::container::Registrar;use dust::foundation::ServiceProvider;use dust::view::{Engine, Html, Template};pub struct Markdown;impl Engine for Markdown {    fn render(&self, template: &Template<'_>) -> dust::Result<Html> {        Ok(Html::raw(markdown::to_html(&template.source()?)))    }}pub struct MarkdownServiceProvider;impl ServiceProvider for MarkdownServiceProvider {    fn register(&self, app: &mut Registrar) {        app.views().engine("md", Markdown);    }}

Any view with that extension is then rendered by your engine, so view("about", ()) renders resources/views/about.md.

Testing views

In your HTTP tests, you may assert which view a response rendered and inspect the data passed to it:

rust
use dust::model::create;use dust::testing::prelude::*;use crate::models::User;#[dust::test]async fn the_users_page_lists_users(app: Application) -> dust::Result<()> {    create!(User { name: "Taylor", email: "taylor@example.com", password: "password" }).await?;    app.get("/users")        .await        .assert_view_is("users.index")        .assert_view_has("users.0.name", "Taylor")        .assert_view_where("users", |users: Vec<User>| users.len() == 1);    Ok(())}

assert_view_has, assert_view_missing, assert_view_present, and assert_view_where support "dot" notation and inspect the data passed directly to view(...) (not data shared globally). To assert on the rendered HTML output itself, use assert_see.