DanielGibbs
DanielGibbs

Reputation: 10190

Accessing external variables from within a Jinja2 macro

I have the following Jinja2 files but the macro do_stuff doesn't appear to be able to access the values of something and something_else that are defined in my_template.jinja2.

Is there a way to make this possible? I'm aware I can pass them in manually to the macro, but as their values stay the same for every invocation of the macro in a template file, it would be nice not to have to do that.

If I embed the macro directly in my_template.jinja2 it works but then it would have to be duplicated across all templates that use it.

macro.jinja2

{% macro do_stuff(value) %}
     <p>Something is {{ something | default('nothing') }}.</p>
     <p>Something else is {{ something_else | default ('nothing') }}.</p>
     <p>Values is {{ value }}.</p>
{% endmacro %}

base_template.jinja2

{% from 'macros.jinja2' import do_stuff %}
{# Other common stuff goes here #}

my_template.jinja2

{% extends 'base_template.jinja2' %}

{% set something = "foo" %}
{% set something_else = "bar" %}

{# Content #}
{{ do_stuff("baz1") }}
{# More content #}
{{ do_stuff("baz2") }}
{# More content #}
{# etc. #}

Upvotes: 3

Views: 1917

Answers (2)

n-a-t-e
n-a-t-e

Reputation: 181

Use with context in the import

{% from 'macros.jinja2' import do_stuff with context%}

See Access Macro Context in Jinja2

Upvotes: 3

DanielGibbs
DanielGibbs

Reputation: 10190

I couldn't find a way to do this and ended up just passing in default arguments every time:

macro.jinja2

{% macro do_stuff(something, something_else, value) %}
    <p>Something is {{ something | default('nothing') }}.</p>
    <p>Something else is {{ something_else | default ('nothing') }}.</p>
    <p>Values is {{ value }}.</p>
{% endmacro %}

my_template.jinja2

{% extends 'base_template.jinja2' %}

{% set something = "foo" %}
{% set something_else = "bar" %}

{# Content #}
{{ do_stuff(something, something_else, "baz1") }}
{# More content #}
{{ do_stuff(something, something_else, "baz2") }}
{# More content #}
{# etc. #}

Upvotes: 0

Related Questions