tera icon indicating copy to clipboard operation
tera copied to clipboard

Macros are unable to use the self:: namespace

Open corentin-cres opened this issue 5 years ago • 3 comments

I was writing a macro using recursive calls and it seems that macros are unable to access the self:: namespace.

I have a base.html file, which is extended by a section.html file, which itself imports a myfactorial.html file containing the macro. For example, straight from the doc :

File myfactorial.html contains :

{% macro factorial(n) %}
  {% if n > 1 %}{{ n }} - {{ self::factorial(n=n-1) }}{% else %}1{% endif %}
{% endmacro factorial %}

File section.html contains :

{% extends "base.html" %}
{%- import "macros/myfactorial.html" as myfactorial %}
{{ myfactorial::factorial(n=3) }}

This does not work and complains that : Failed to render 'section.html': error while rendering macro myfactorial::factorialReason: Macroself::factorialnot found in templatesection.html``

There seems to be some clue that context may be badly defined when nesting {% extends %} / {% import %} : The self namespace does exist, but it appears to be assigned to the first import of the two in the rendered template. https://github.com/Keats/tera/pull/548

corentin-cres avatar Oct 12 '20 09:10 corentin-cres

Just a small workaround I found in case someone wants to use recursive calls anyways :

{{ self::factorial(n=n-1) }} being replaced by {{ myfactorial::factorial(n=n-1) }} works.

That weighs even more in favor of the self namespace being badly defined as the parent scope.

corentin-cres avatar Oct 14 '20 13:10 corentin-cres

I haven't used self in macros since it was implemented. My (very) vague recollection is that it refers to macros defined on the same file but I could be wrong.

Keats avatar Oct 14 '20 18:10 Keats

For me self works within a file (e.g. macros.html) that is imported via: {% import "macros.html" as macros %}

If I import another macro file from within macros.html: e.g.: {% import "sub_macros.html" as sub_macros %}

Then within sub_macros.html I cannot use self anymore.

@johndoudou's workaround for the rescue!

tobx avatar Feb 11 '22 16:02 tobx