Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Macro Recursion in Jinja2

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?

like image 435
awatts Avatar asked Sep 24 '15 22:09

awatts


2 Answers

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  
like image 53
pvpks Avatar answered Oct 01 '22 23:10

pvpks


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.

like image 42
Hanshan Avatar answered Oct 01 '22 22:10

Hanshan