Macro recursion in Jinja2

I am using the Jinja 2.8 templating engine. I am trying to write a template that will move through a tree structure and output information from this tree. For this, I'm trying to use a macro that calls itself, which doesn't seem to work.

This simple recursive macro also does not work:

{% macro factorial(n) %}
  {% if n > 1 %}
    {{ n }} * {{ factorial(n-1) }}
  {% endif %}
{% endmacro %}

{{ factorial(3) }}

When you run the next error, it rises on the third line of Jinja code.

UndefinedError: 'factorial' is undefined

Does Jinja support recursive macros? How else can you lay out a nested data structure in Jinja?

+4
source share
2 answers

Jinja supports recursive macros.
As for factorial, 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

--7--6--5--4--3--2--1  
    5040  
+1

, if, , , if false.

, if - {% block content %}, .

, , .

0

Source: https://habr.com/ru/post/1608903/


All Articles