Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
MarcusSanchez opened this issue Oct 8, 2023 · 4 comments
Open

Comments

@MarcusSanchez
Copy link

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
Copy link
Owner

Keats commented Oct 8, 2023

This will probably be added in v2

@GandelXIV
Copy link

@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
Copy link

We could also get inspiration from minijinja's implementation

@GandelXIV
Copy link

Made a pull request #887

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants