Check if an array is not empty in Jinja2

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

    This is what worked for my use case in my Django app:

    I needed to pass a queryset as context to an html template and display the block only if the queryset had values

    Queryset:

    events = Event.objects.filter(schedule_end__gte=date.today()).order_by('-created_at')
    

    Passed context dictionary as follows:

    { "events" : events }
    

    HTML template

    {% if events %}
      

    Upcoming Events

      {% for event in events %}
    • {{ event.title }}

    • {% endfor %}
    {% endif %}

提交回复
热议问题