Keats / tera

A template engine for Rust based on Jinja2/Django
http://keats.github.io/tera/
MIT License
3.43k stars 279 forks source link

[FEATURE REQUEST] Macros for making Context have less boilerplate #861

Open MarcusSanchez opened 11 months ago

MarcusSanchez commented 11 months ago

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.

Keats commented 11 months ago

This will probably be added in v2

GandelXIV commented 8 months ago

@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
};
GandelXIV commented 8 months ago

We could also get inspiration from minijinja's implementation

GandelXIV commented 8 months ago

Made a pull request #887