1

I want to make a counter this simple code not working...

  {% set count = 1 %}
  {% for i in [1,2,3,4,5] %}
      {% set count = count + 1 %}
  {% endfor %}
  <h2>found {{count}}<h2>

the result is 1 i see you can use this How to increment a variable on a for loop in jinja template? but this is not work for me

  • 1
    Is there a reason that you don't use the built-in loop counter? [There are several](https://stackoverflow.com/a/24959173/4799172) – roganjosh Dec 27 '18 at 20:18
  • If you want to see the incremental value, the

    tag should be inside the for loop.

    – amanb Dec 27 '18 at 20:23

2 Answers2

1

If you're using Flask and Jinja2, you can use the built in filter length.

{% set my_list = [1,2,3,4,5] %}
{% for i in my_list %}
    ...  
{% endfor %}
<h2>found {{my_list|length}}<h2>

If that doesn't do exactly what you want, you can also expose custom filter or functions from your Flask app when it is initialized by using add_template_filter() or add_template_global()

minboost
  • 2,555
  • 1
  • 15
  • 15
1

There are situations where it's more appropriate to do the counting prior to template rendering, passing the count in to the template. You might be looking at one of those. The Jinja2 template "language" is not a full, turing-complete programming language.

Dave W. Smith
  • 24,318
  • 4
  • 40
  • 46