Check if an array is not empty in Jinja2

后端 未结 7 1124
萌比男神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:25

    To test for presence ("defined-ness"?), use is defined.

    To test that a present list is not empty, use the list itself as the condition.

    While it doesn't seem to apply to your example, this form of the emptiness check is useful if you need something other than a loop.

    An artificial example might be

    {% if (texts is defined) and texts %}
        The first text is {{ texts[0] }}
    {% else %}
        Error!
    {% endif %}
    

提交回复
热议问题