I'm using Jinja 2.8 templating engine. I'm trying to write a template which will walk over a tree structure and output information from that tree. To do this I'm trying to use a macro which calls itself which doesn't seem to work.
This simple recursive macro also doesn't work:
{% macro factorial(n) %}
{% if n > 1 %}
{{ n }} * {{ factorial(n-1) }}
{% endif %}
{% endmacro %}
{{ factorial(3) }}
When run following error is raised on the third line of Jinja code.
UndefinedError: 'factorial' is undefined
Does Jinja support recursive macros? How else could a nested data-structure be traversed in Jinja?
Jinja supports recursive macros.
Regarding the factorial code, the following code works for me:
{% macro factorial(n,return_value) -%}
--{{n}}
{%- if n > 1 -%}
{%- set return_value = n * return_value %} {#- perform operations on the variable return_value and send it to next stage -#}
{{- factorial(n-1,return_value) -}}
{%- else -%} {# Output the return value at base case #}
{{ return_value }}
{%- endif %}
{%- endmacro %}
{{ factorial(7,1) }}
The output I got is
--7--6--5--4--3--2--1 5040
I came across this issue, and noticed my macro definition was sitting in an if
block, which means it won't be there if the if
evaluates to false.
But it did not work when I moved the definition just above the if
blocks - I had to move it above my {% block content %}
before I could get it to work.
I would suggest your code might be sitting nested amongst some other code that will be preventing it from being found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With