Macro rocket_dyn_templates::minijinja::context

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

Creates a template context from keys and values or merging in another value.

let ctx = context!{
    name => "Peter",
    location => "World",
};

Alternatively if the variable name matches the key name it can be omitted:

let name = "Peter";
let ctx = context!{ name };

The return value is a Value.

Note that context! can also be used recursively if you need to create nested objects:

let ctx = context! {
    nav => vec![
        context!(path => "/", title => "Index"),
        context!(path => "/downloads", title => "Downloads"),
        context!(path => "/faq", title => "FAQ"),
    ]
};

Additionally the macro supports a second syntax that can merge other contexts or values. In that case one or more values need to be passed with a leading .. operator. This is useful to supply extra values into render in a common place. The order of precedence is left to right:

let ctx = context! { a => "A" };
let ctx = context! { ..ctx, ..context! {
    b => "B"
}};

// or

let ctx = context! {
    a => "A",
    ..context! {
        b => "B"
    }
};

The merge works with an value, not just values created by the context! macro and is performed lazy. This means it also works with dynamic Objects.

§Note on Conversions

This macro uses Value::from_serialize for conversions.

This macro currently does not move passed values. Future versions of MiniJinja are going to change the move behavior and it’s recommended to not depend on this implicit reference behavior. You should thus pass values with &value if you intend on still being able to reference them after the macro invocation.