Check if an array is not empty in Jinja2

后端 未结 7 1123
萌比男神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.

    0 讨论(0)
  • 2021-02-06 21:05

    This is a neat and simple solution that worked well for me!

    {% if texts is defined and texts[0] is defined %}
        ...
    {% endif %}
    
    0 讨论(0)
  • 2021-02-06 21:22

    I think your best bet is a combination of defined() check along with looking at the length of the array via length() function:

    {% if texts is defined and texts|length > 0 %}
        ...
    {% endif %}
    
    0 讨论(0)
  • 2021-02-06 21:22

    As mentioned in the documentation, you could also write:

    {% for text in texts %}
        <div class="post">
            <div class="post-title">{{text.subject}}</div>
            <pre class="post-content">{{text.content}}</pre>
        </div>
    {% else %}
        <div>{{ error }}</div>
    {% endfor %}
    

    It handles both the case where texts is undefined, and the case where texts is empty.

    0 讨论(0)
  • 2021-02-06 21:23

    Take a look at the documentation of Jinja2 defined(): http://jinja.pocoo.org/docs/templates/#defined

    {% if variable is defined %}
        value of variable: {{ variable }}
    {% else %}
        variable is not defined
    {% endif %}
    

    Is it clear enough? In your case it could look like this:

    {% if texts is defined %}
        {% for text in texts %} 
            <div>{{ error }}</div>
            <div class="post">
                <div class="post-title">{{ text.subject }}</div>
                <pre class="post-content">{{ text.content }}</pre>
            </div>
        {% endfor %}
    {% else %}
        Error!
    {% endif %}
    
    0 讨论(0)
  • 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 %}
      <h3>Upcoming Events</h3>
      <ul>
        {% for event in events %}
        <li><h4>{{ event.title }}</h4></li>
        {% endfor %}
      </ul>
    {% endif %}
    
    0 讨论(0)
提交回复
热议问题