4

When is it advisable or prudent to use without rather than a conditional statement to exclude something, eg a set of entries, based on one parameter?

For example, say I have real towns and fictional Towns that are listed on a related Regional page. These Towns are sorted real/fictional by a toggle field -- 0 for real, 1 for fictional.

The fictional towns are used elsewhere and should not be listed on any Regional page. In this case, should I be using if (see below) or without?

Here is how I am doing it right now in my Regional template:

{% if town.townFictional == 0 %}
    <li>{{town.link}}</li>
{% endif %}

This is working fine, but I came across this question where using without was suggested.

Is without preferred in my case, and if so how do I use it? Here is my towns variable:

{% set towns = craft.entries.section('towns').relatedTo(counties) %}

1 Answer 1

8

For your example, you should exclude the fictional towns in the initial query itself rather than filtering them out afterwards:

{% set towns = craft.entries.section('towns').townFictional('not 1').relatedTo(counties) %}

So that no towns with the Fictional Lightswitch on will be returned from the database at all.

You would use the |without filter, if you already had an array of items and you wanted to filter some of them out while looping over them. This works best with arrays of simple primitives, such as an array of entry IDs, rather than whole objects.

You would be more likely to use an {% if %} tag if you still wanted to fetch the entry, but wanted to adjust some part of your output based on a condition. So for example if you had an array of entries from different sections, and they might not all have URLs, you might decide to output a link or just the title:

{% for entry in entries %}
    {% if entry.getUrl() %}
        <li><a href="{{ entry.getUrl()">{{ entry.title }}</a></li>
    {% else %}
        <li>{{ entry.title }}</li>
    {% endif %}
{% endfor %}
4
  • Excellent. Thank you. I'm trying to make my code more economical, which can be a little tough when you're teaching yourself as you go! Thanks again! Nov 2, 2016 at 16:07
  • Would you be able to expound a little further and explain when without would be a better option? Nov 3, 2016 at 16:43
  • 1
    A quick followup for anyone who may have experienced some hiccups using this method later on. Sometimes lightswitchField(0) won't work, it will return all entries. Using lightswitchField('not 1') resolved this. See craftcms.stackexchange.com/questions/11911/… Nov 4, 2016 at 16:15
  • Ah, yes, thank you. I've updated this answer :) Nov 4, 2016 at 16:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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