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

Context not passed into state of custom functions when called within macro #535

Open
mbund opened this issue Jul 8, 2024 · 0 comments
Open

Comments

@mbund
Copy link

mbund commented Jul 8, 2024

Description

When adding a function with add_function that accepts a &minijinja::State, the context provided at the "global" scope (with the context! macro) doesn't get passed in when within a macro's {% call %} block.

Reproduction steps

A reproduction repo can be found here.

Consider the following custom function myfunc

fn jinja_myfunc(state: &minijinja::State) -> String {
    let global = state.lookup("my_global");

    match global {
        Some(_) => "global exists".to_owned(),
        None => "global DOES NOT exist".to_owned(),
    }
}

And template main

{% macro wrapper() %} <wrapper>{{ caller() }}</wrapper> {% endmacro %}

{{ myfunc() }}

{% call wrapper() %}
  {{ var_a }}
  {{ myfunc() }}
{% endcall %}

{% call wrapper() %}
  {% with lift_global_up=my_global %}{% endwith %}
  {{ var_a }}
  {{ myfunc() }}
{% endcall %}

Now, rendering main with context! { var_a => "v_a", my_global => "my_global" } currently produces the following output:

global exists

<wrapper>
  v_a
  global DOES NOT exist
</wrapper>

<wrapper>

  v_a
  global exists
</wrapper>

The function myfunc expects the variable my_global to be in the current global state. Normally it exists "passively" as shown by the first global exists at the top. However, when entering the macro scope wrapper, the my_global variable is forgotten about even though the function requires looking it (as shown by the global DOES NOT exist).

The third <wrapper> shows my current workaround, where I can "lift" the variables I know my function needs into the current macro scope so the function runs properly.

Additional helpful information:

  • Version of minijinja: 2.0.3
  • Version of rustc: rustc 1.76.0 (07dca489a 2024-02-04)
  • Operating system and version: Fedora Linux 40.20240703.0 (Silverblue)

What did you expect

Variables passed in when rendering a template (with the render function and context! macro), should always be visible in minijinja state. The state should not be forgotten about when entering into a macro call.

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

1 participant