I have the following Jinja template:
{% set mybool = False %}
{% for thing in things %}
{%
Had a need to find the max num of entries in an object (object) from a list (objects_from_db),
This did not work for reasons known in jinja2 and variable scope.
{% set maxlength = 0 %}
{% for object in objects_from_db %}
{% set ilen = object.entries | length %}
{% if maxlength < ilen %}
{% set maxlength = ilen %}
{% endif %}
{% endfor %}
Here's what works:
{% set mlength = [0]%}
{% for object in objects_from_db %}
{% set ilen = object.entries | length %}
{% if mlength[0] < ilen %}
{% set _ = mlength.pop() %}
{% set _ = mlength.append(ilen)%}
{% endif %}
{% endfor %}
{% set maxlength = mlength[0] %}
Hope this helps someone else trying to figure out the same.
When writing a contextfunction()
or something similar you may have noticed that the context tries to stop you from modifying it.
If you have managed to modify the context by using an internal context API you may have noticed that changes in the context don’t seem to be visible in the template. The reason for this is that Jinja
uses the context only as primary data source for template variables for performance reasons.
If you want to modify the context write a function that returns a variable instead that one can assign to a variable by using set:
{% set comments = get_latest_comments() %}
Source