0

I'd like to iterate over a set of objects and find the maximum of one particular attribute, however jinja2 ignores any action within an iterator on a variable declared outside of the iterator. For example:

{% set maximum = 1 %}
{% for datum in data %}
    {% if datum.frequency > 1 %}
        {% set maximum = datum.frequency %}
    {% endif %}
{% endfor %}
{# maximum == 1 #}

datum.frequency is definitely greater than 1 for some datum in data.

EDIT (solution)

This is similar to this post, but there's a bit more to it. The following works and is very ugly.

{% set maximum = [1] %}
{% for datum in data %}
    {% if datum.freq > maximum[-1] %}
        {% if maximum.append( datum.freq ) %}{% endif %}
    {% endif %}
{% endfor %}
{% set maximum = maximum[-1] %}
Community
  • 1
  • 1
astex
  • 1,045
  • 10
  • 28

1 Answers1

1

Have you considered writing a custom filter to return the highest value of a particular attribute within your collection? I prefer to minimize the amount of logic I use in Jinja2 templates as part of maintaining a 'separation of concerns'.

Here is a link to a very good example of how one can be written in python: Custom jinja2 filter for iterator

Once you have your filter returning the value you need access it by using '|' like so:

{% set maximum = datum|filtername %}
Community
  • 1
  • 1
Nickel
  • 533
  • 1
  • 7
  • 20