tera
tera copied to clipboard
[FEATURE REQUEST] Macros for making Context have less boilerplate
Make a macro that allows quick Context for easy drop in values. Something like this:
#[macro_export]
macro_rules! ctx {
({
$($key:literal : $value:expr),* $(,)?
}) => {
{
let mut ctx = Context::new();
$(
ctx.insert($key, $value);
)*
ctx
}
};
}
That allows this:
let mut context = Context::new();
context.insert("Hello", "world");
context.insert("answer", &42);
context.insert("person", &person);
to turn into:
let context = ctx!({
"hello": "world",
"answer": &42,
"person": &person
});
The exact syntax for the macro doesn't really matter, anything really will be nice, just not a context.insert() every line, this will also make it easier to pass these as parameters.
This will probably be added in v2
@MarcusSanchez I wrote this very simple implementation for my personal projects:
#[macro_export]
macro_rules! context {
(
$(
$key:ident $(=> $value:expr)? $(,)*
)*
) => {
{
let mut context = Context::new();
$(
context.insert(stringify!($key), $($value)?);
)*
context
}
};
}
Using it this way:
let ctx = context! {
name => "Jack",
age => 24
};
Expands to:
let ctx = {
let mut context = Context::new();
context.insert("name", "Jack");
context.insert("age", 24);
context
};
We could also get inspiration from minijinja's implementation
Made a pull request #887