Redefining imported jinja macros

So with the help of my colleague, I figured it out.

the parent template evaluated after the child one
http://jinja.pocoo.org/docs/dev/faq/#my-macros-are-overridden-by-something

that means if you want to use second option you just have to check the macro for existence in parent template.

Works like this:

{# macros.html #}
{% if not a %}
{% macro a(opts = {}) %}
   {{ opts.a }}
{% endmacro %}
{% endif %}

{% if not b %}
{% macro b(opts = {}) %}
   {{ opts.b }}
{% endmacro %}
{% endif %}

and this one which contains the override

{# macros_override.html #}
{% extends 'macros.html' %}
{% if not a %}{# I repeat here in case there's gonna be a double extend #}
{% macro a(opts = {}) %}
    Overridden: {{ opts.a }}
{% endmacro %}
{% endif %}

and the just import them like this

{# template.html #}
{% import 'macros_override.html' as macros %}

{{ macros.a({ 'a': 'foo' }) }}
{{ macros.b({ 'b': 'bar' }) }}

and it outputs as expected

Overridden: foo
bar

Tags:

Jinja2