Using {{ caller() }} within {% call %} fails
See original GitHub issueThe actual template where I encountered the issue first was more boilerplate-ish, but I this one describes the problem in a more intuitive way.
Suppose we have the following template:
{%- macro _tag(tag, id=none, classes=(), attrs={}) -%}
<{{ tag }}
{% if id %} id="{{ id }}" {% endif %}
{% if classes %} class="{{ classes|join(' ') }}" {% endif %}
{{ attrs|xmlattr }}>
{% if caller %} {{ caller() }} {% endif %}
</{{ tag }}>
{%- endmacro -%}
along with a higher level template that tries to {% call %}
it for some specific case:
{%- macro _div() -%}
{% call _tag('div', *varargs, **kwargs) %}
{% autoescape false %}
{% if caller %} {{ caller() }} {% endif %}
{% endautoescape %}
{% endcall %}
{%- endmacro -%}
Intuitively, doing {% call _div(...) %} <b>foo</b> {% endcall %}
should pass <b>foo</b>
to the _tag
macro, which would then render it (verbatim, thanks to autoescape). But the actual result is UndefinedError: No caller defined
on the {{ caller() }}
line inside _div
. It would seem that the scope of caller
does not extend into the {% call %}
block, thereby preventing chained calls such as the one depicted above.
There is an ugly workaround that uses the new block assignment feature from 2.8:
{%- macro _div() -%}
{% set content %}
{% if caller %} {{ caller() }} {% endif %}
{% endset %}
{% call _tag('div', *varargs, **kwargs) %}
{% autoescape false %} {{ content }} {% endautoescape %}
{% endcall %}
{%- endmacro -%}
but, of course, the original version would be much more preferable.
Issue Analytics
- State:
- Created 9 years ago
- Reactions:1
- Comments:5 (3 by maintainers)
Small note about the workaround:
The new feature of 2.8 is not needed as this is also working fine:
Yeah, we might want to put that into the docs.