Check if an array is not empty in Jinja2

后端 未结 7 1132
萌比男神i
萌比男神i 2021-02-06 20:48

I need to check if the variable texts is defined or not in index.html.

If the variable is defined and not empty then I should render the loop.

7条回答
  •  野的像风
    2021-02-06 21:04

    It's possible that texts could be defined but contain a single list element which is an empty string; For example:

    texts = ['']
    

    In this case, testing if texts is defined will produce a true result so you should test the first element instead:

    {% if texts[0] != '' %}
        ..code here..
    {% endif %}
    

    You might also want to combine that with the |length filter to make sure it only has one element.

提交回复
热议问题