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

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

I have the following Jinja template:

{% set mybool = False %}
{% for thing in things %}
    
    {%
8条回答
  •  清歌不尽
    2020-11-27 06:33

    You can solve your problem using this hack (without extensions):

    import jinja2
    
    env = jinja2.Environment()
    print env.from_string("""
    {% set mybool = [False] %}
    {% for thing in things %}
        
      {% if current_user %} {% if current_user.username == thing['created_by']['username'] %} {% set _ = mybool.append(not mybool.pop()) %}
    • mybool: {{ mybool[0] }}
    • Edit
    • {% endif %} {% endif %}
    • Flag

    {% endfor %} {% if not mybool[0] %}

    mybool is false!

    {% else %}

    mybool is true!

    {% endif %} """).render(current_user={'username':'me'},things=[{'created_by':{'username':'me'}},{'created_by':{'username':'you'}}])

提交回复
热议问题