6

I thought this would be very easy but I'm having a hard time figuring it out.

How do you output a warning/message if there are no entries to loop through?

{% set entries = craft.entries.section('news').limit(5).find() %}

{% if entries|length %}
    {% for entry in entries %}
      {# Do Loop #}
    {% endfor %}
{% else %}
    <p>No entries found.</p>
{% endif %}

Or am I just sleepy and approaching this all wrong?

12

The for tag has an else clause by which you can render a replacement block if no iteration took place because the sequence was empty.

<ul>
    {% for user in users %}
        <li>{{ user.username|e }}</li>
    {% else %}
        <li><em>no user found</em></li>
    {% endfor %}
</ul>

reference: http://twig.sensiolabs.org/doc/tags/for.html#the-else-clause

  • I thought I had, I think my internet connection glitched when I did. Thanks for letting me know! – cballenar Jul 12 '14 at 1:54
  • Oh, wait... No. I can do it in 14 hours :P – cballenar Jul 12 '14 at 1:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.