In Jinja2, how to create auto increment numbers?

Viewed 80

In a page, I want to display some figures with text prompt. For example:

Figure 1
Figure 2

My code is

{% set num = 0 %}
Figure {{ ++num }}
Figure {{ ++num }}

But it shows

Figure 0
Figure 0

How can I make it fulfil my expectations?

1 Answers

Either those text prompt are in a list already, and you can use a for to display them, along with loop.index for the numbering:

{% set texts = ['foo', 'bar', 'baz'] %}

{%- for text in texts -%}
  Figure {{ loop.index }}
  {{ text }}

{% endfor -%}

Will render

Figure 1
  foo

Figure 2
  bar

Figure 3
  baz

Or, they are in another format and you will have to use a set to increment your counter:

{% set foo = 'foo' -%}
{% set bar = 'bar' -%}
{% set baz = 'baz' -%}
{% set counter = 1 -%}

Figure {{ counter }}
  {{ foo }}

{% set counter = counter + 1 -%}
Figure {{ counter }}
  {{ bar }}

{% set counter = counter + 1 -%}
Figure {{ counter }}
  {{ baz }}

Which will render the same.

Related