Can a Jinja variable's scope extend beyond in an inner block?

后端 未结 8 836
夕颜
夕颜 2020-11-27 06:07

I have the following Jinja template:

{% set mybool = False %}
{% for thing in things %}
    
    {%
相关标签:
8条回答
  • 2020-11-27 06:48

    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.

    0 讨论(0)
  • 2020-11-27 06:49

    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

    0 讨论(0)
提交回复
热议问题