rocket_dyn_templates

Macro context

Source
macro_rules! context {
    ($($key:ident $(: $value:expr)?),*$(,)?) => { ... };
}
Expand description

A macro to easily create a template rendering context.

Invocations of this macro expand to a value of an anonymous type which implements Serialize. Fields can be literal expressions or variables captured from a surrounding scope, as long as all fields implement Serialize.

§Examples

The following code:

#[get("/<foo>")]
fn render_index(foo: u64) -> Template {
    Template::render("index", context! {
        // Note that shorthand field syntax is supported.
        // This is equivalent to `foo: foo,`
        foo,
        bar: "Hello world",
    })
}

is equivalent to the following, but without the need to manually define an IndexContext struct:

#[derive(Serialize)]
struct IndexContext<'a> {
    foo: u64,
    bar: &'a str,
}

#[get("/<foo>")]
fn render_index(foo: u64) -> Template {
    Template::render("index", IndexContext {
        foo,
        bar: "Hello world",
    })
}

§Nesting

Nested objects can be created by nesting calls to context!:

let ctx = context! {
    planet: "Earth",
    info: context! {
        mass: 5.97e24,
        radius: "6371 km",
        moons: 1,
    },
};