dust

Head Metadata

Introduction

A page's <head> carries the title search results and browser tabs show, the description a search engine may quote, and the Open Graph and Twitter tags that decide how a link looks when someone shares it. Rendering those tags on the server means crawlers and chat apps see them without running JavaScript.

You describe metadata with a Head value. Your application sets global defaults, routes may add static metadata, and handlers merge request-specific metadata before returning a response. For example, this handler sets a product's title and description from its model fields:

rust
use dust::head::{self, Head};use dust::prelude::*;use dust::view::View;use crate::models::Product;pub async fn show(product: Product) -> dust::Result<View> {    head::merge(Head::new().title(&product.name).description(&product.summary));    Ok(view("products.show", data! { product }))}

Rendering the head

dust-framework merges the metadata for a request into one Head value and renders it when your layout calls head(). The route, the handler's head::merge calls, and the global defaults are all resolved before the view is rendered, so the helper always prints the final tags.

In views

Call head() inside your layout's <head>, right after static tags such as charset and viewport:

html
<!-- resources/views/layouts/app.html --><head>    <meta charset="utf-8">    <meta name="viewport" content="width=device-width, initial-scale=1">    {{ head() }}</head>

Because the head renders alongside the view, call head::merge before your handler returns. Load your stylesheets and scripts after {{ head() }}, so the canonical link and social tags appear as early as possible in the document.

Setting defaults

Out of the box, dust-framework appends your application's name to every page title, such as About · dust-framework. Most applications also want a default description, canonical URL, and social tags on every page. Configure defaults inside with_head in src/app.rs:

rust
use dust::head::{Head, OgType, TwitterCard};use dust::prelude::*;Application::configure()    .with_head(|head, config| {        head.defaults(            Head::new()                .description("Build something great.")                .canonical()                .og_type(OgType::Website)                .og_site_name(&config.app.name)                .twitter_card(TwitterCard::SummaryLargeImage),        );    })

canonical() outputs a <link rel="canonical"> tag for the current URL without its query string, so /products?utm_source=news and /products share one canonical URL. To preserve specific query parameters such as pagination, use canonical_with_query(["page"]). To point at a different URL altogether, use canonical_url("/products/1").

Titles

Page titles are formatted through a title template where %s is replaced by the page's title. By default, the template is %s · {app name}, so title("About") renders About · dust-framework. Pages without a title render your application's name alone, and a title(...) set in global defaults renders as written without the template.

To customize the template globally or for a route group (such as an admin area), call title_template. To bypass the template on a single page, use exact_title:

rust
Head::new().title_template("%s | dust-framework News")Head::new().exact_title("dust-framework | The Rust Web Framework")

Error pages

By default, every error page uses its HTTP status reason as its title, such as Not Found · dust-framework. Since search engines shouldn't index error pages (and a 404 page benefits from a clearer description), configure error metadata inside with_head using errors for all error pages and error for a specific status code:

rust
use dust::head::{Head, Robots};use dust::prelude::*;Application::configure()    .with_head(|head, _| {        head.errors(Head::new().robots([Robots::NoIndex, Robots::Follow]));        head.error(            404,            Head::new().description("The page you are looking for could not be found."),        );    })

Metadata for routes

Error metadata overrides any route or handler metadata and applies to error views and custom renderers. Error pages omit the canonical link unless your error metadata sets one explicitly.

When a page's metadata is static, such as a contact page's title or a robots rule for an entire admin area, attach a Head directly to a route, route group, or resource route with with_head:

rust
use dust::head::{Head, Robots};use dust::prelude::*;pub fn routes(route: &mut Router) {    route        .view("/contact", "contact")        .with_head(Head::new().title("Contact Us").description("Get in touch."));    route        .with_head(Head::new().robots(Robots::None))        .prefix("/admin")        .group(|route| {            route                .get("/dashboard", admin::dashboard)                .with_head(Head::new().title("Dashboard"));        });}

When nested groups or a route set the same tag, dust-framework uses the most specific value: the route's metadata overrides its group's, and an inner group's metadata overrides an outer group's.

Metadata for a page

Most metadata depends on the current request, such as the name and photo of a specific product. Call head::merge in a handler or middleware before the response renders. You may call head::merge multiple times during a request, and later calls override earlier ones.

For example, this handler sets a product's Open Graph image from its image_url and image_alt columns, and hides unpublished drafts from search engines:

rust
use dust::head::{self, Head, OgImage, OgType};use dust::prelude::*;use dust::view::View;use crate::models::Product;pub async fn show(product: Product) -> dust::Result<View> {    head::merge(        Head::new()            .title(&product.name)            .og_type(OgType::Website)            .og_image(                OgImage::new(&product.image_url)                    .alt(&product.image_alt)                    .size(1200, 630),            ),    );    if product.published_at.is_none() {        head::merge(Head::new().hidden_from_robots());    }    Ok(view("products.show", data! { product }))}

Because head::merge accepts anything that implements Into<Head>, you may implement From<&Product> for Head next to your model and pass a reference to the model directly in your handler:

rust
use dust::head::Head;impl From<&Product> for Head {    fn from(product: &Product) -> Self {        Head::new().title(&product.name).description(&product.summary)    }}
rust
pub async fn show(product: Product) -> dust::Result<View> {    head::merge(&product);    Ok(view("products.show", data! { product }))}

How layers combine

dust-framework merges metadata from five layers, from lowest priority to highest:

  1. Your application's name, used as the fallback title.
  2. Global defaults registered with head.defaults(...) in src/app.rs.
  3. Metadata attached to route groups, followed by metadata attached directly to the route.
  4. Each head::merge(...) call made during the request, in the order called.
  5. On error responses, the HTTP status reason as the title, followed by head.errors(...) and head.error(status, ...).

For single-value tags such as title or description, the highest layer takes precedence while lower layers retain their other tags (so a route's description stays intact when a handler only sets the title). Repeatable tags such as alternate languages are combined unless a higher layer defines the same entry again. A page's Open Graph images, videos, or audio files replace those from the global defaults so a product's photo isn't rendered alongside your site's default social image.

Open Graph and Twitter

When someone shares a link on social media or in a chat app, link previews read the page's Open Graph and Twitter Card tags. With the global defaults configured earlier, calling head::merge in the /products/1 handler:

rust
use dust::head::{self, Head, OgImage};head::merge(    Head::new()        .title("Trail Running Shoes")        .description("Lightweight waterproof shoes built for mountain trails.")        .og_image(OgImage::new("/images/shoes.jpg").alt("Trail Running Shoes")),);

produces the following tags in the document's <head>:

html
<title>Trail Running Shoes · dust-framework</title><meta name="description" content="Lightweight waterproof shoes built for mountain trails."><link rel="canonical" href="https://example.com/products/1"><meta property="og:type" content="website"><meta property="og:site_name" content="dust-framework"><meta property="og:title" content="Trail Running Shoes · dust-framework"><meta property="og:description" content="Lightweight waterproof shoes built for mountain trails."><meta property="og:image" content="https://example.com/images/shoes.jpg"><meta property="og:image:alt" content="Trail Running Shoes"><meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="Trail Running Shoes · dust-framework"><meta name="twitter:description" content="Lightweight waterproof shoes built for mountain trails."><meta name="twitter:image" content="https://example.com/images/shoes.jpg"><meta name="twitter:image:alt" content="Trail Running Shoes">

Once a page has any Open Graph tag, og:title and og:description fall back to the page's title and description automatically. Similarly, once a page has a Twitter tag (such as the default card), Twitter tags fall back to the Open Graph values. Any value you set explicitly with og_title, og_description, twitter_title, twitter_description, or twitter_image always takes precedence over these fallbacks.

Relative image paths such as /images/shoes.jpg are automatically expanded to absolute URLs, since social crawlers require full URLs.

Icons, hints, and other tags

Browsers also read <head> for favicons, theme colors, resource preloads, and RSS or Atom feeds. Most applications configure these once in head.defaults(...) inside with_head:

rust
use dust::head::{Feed, Head, Icon, ImageType, Link, Media, Preload};head.defaults(    Head::new()        .theme_color("#ffffff")        .theme_color_for(Media::Dark, "#111827")        .icon(Icon::new("/favicon.svg").mime(ImageType::Svg))        .apple_touch_icon(Icon::new("/apple-touch-icon.png").sizes("180x180"))        .manifest("/site.webmanifest")        .preconnect("https://fonts.bunny.net")        .preload("/fonts/inter.woff2", Preload::Font)        .alternate("fr", "https://example.com/fr/about")        .feed(Feed::atom("/feed.atom").title("dust-framework Atom"))        .meta("format-detection", "telephone=no")        .link(            Link::new("search", "/opensearch.xml")                .attr("type", "application/opensearchdescription+xml"),        ),);

For any tag without a dedicated helper method, use meta or link as shown in the last two lines.

On paginated pages, pass your paginator to paginated. It keeps the paginator's page parameter (such as page or cursor) in the canonical URL and emits <link rel="prev"> and <link rel="next"> tags when neighboring pages exist:

rust
use dust::head::{self, Head};use dust::prelude::*;use dust::view::View;use crate::models::Product;pub async fn index() -> dust::Result<View> {    let products = Product::query().order_by(Product::id).paginate(15).await?;    head::merge(Head::new().paginated(&products));    Ok(view("products.index", data! { products }))}

If you build pagination links by hand instead of using a paginator, set canonical_with_query(["page"]), prev_page, and next_page directly.

Structured data

Search engines read JSON-LD structured data to display rich results, such as a product's price and stock status next to its search listing. Call schema on a Head to emit JSON-LD scripts. The dust::head::schema module includes builders for Article, BlogPosting, Product, Offer, Brand, Breadcrumbs, Faq, Organization, Person, WebPage, and WebSite:

rust
use dust::head::schema::{Availability, Breadcrumbs, Offer, Product};use dust::head::{self, Head};head::merge(    Head::new()        .schema(            Product::new().name("Running shoes").offers(                Offer::new()                    .price(49.99)                    .currency("USD")                    .availability(Availability::InStock),            ),        )        .schema(            Breadcrumbs::new()                .item("Home", "https://example.com")                .item("Shop", "https://example.com/shop"),        ),);

For any other schema.org type, build it dynamically with Thing, such as Thing::new("Recipe").set("name", "Pancakes"). If you reuse a custom schema type across your application, implement Schema for a Serialize struct:

rust
use dust::head::schema::Schema;#[derive(Serialize)]#[serde(rename_all = "camelCase")]struct JobPosting {    title: String,}impl Schema for JobPosting {    fn schema_type(&self) -> &str {        "JobPosting"    }}

Omit empty fields rather than passing empty strings or None. In debug mode, a schema containing an empty value fails to render and reports the offending field path; in production, dust-framework logs a warning and omits the schema.

Testing the head

Call assert_head() on a response to inspect the rendered <head> with the same assertions for every page. It reads the metadata dust-framework actually sent, so a test catches a missing default or a handler that forgot to merge its title.

rust
use dust::testing::prelude::*;#[dust::test]async fn product_pages_have_social_tags(app: Application) {    app.get("/products/1")        .await        .assert_head()        .title("Trail Running Shoes · dust-framework")        .meta("og:title", "Trail Running Shoes · dust-framework")        .link("canonical", "http://localhost/products/1")        .schema("Product")        .missing("robots");}
Assertion What it checks
title(text) That the head contains a single <title> with the given text.
meta(name, content) That a <meta> tag with the given name or property has the expected content.
link(rel, href) That a <link> tag has the given rel and URL.
schema(type) That a JSON-LD schema has the given @type, such as Product.
has(key), missing(key) That a tag matching the key exists or is absent (such as robots, og:title, or canonical).