4

What's the correct way to create a conditional so that a field won't display if it's empty? Is it:

{% if entry.myentry | length %}
    ...
{% endif %} 

or

{% if entry.myentry %}
    ...
{% endif %}

I tried both and both seem to work, but I want to make sure they're both correct.

4

It depends on the field type. If it is an entry (or asset or user), then entry.myentry will be an ElementCriteriaModel, which even if there are no elements will always be 'truthy'. In that case, you need entry.myentry|length.

Otherwise, depending on what you want to do about the field being 0 or false you may want one of:

  • entry.myentry : true/false determined as in php. twig if documentation explains this.
  • entry.myentry is not empty - false for null, false, empty array or empty string. (empty)
  • entry.myentry is not null - false for null. (null)
  • entry.myentry|length - this will be 0 if entry.myentry is false or null and 1 if entry.myentry is 0. (length)

I personally would {{ dump(entry.myentry) }} for one of your "empty" entries to get more clarity on which of these would be best.

7

It depends. Technically to determine if a variable is not empty (keep in mind '0' or 'false' are not considered empty), you can use Twig's 'is not empty':

{% if entry.myField is not empty %}...{% endif %}

But in most situations where '0' and/or 'false' are not expected values, then anything that evaluates to '0', 'false' or 'null' will also work. So,

{% if entry.myField %}...{% endif %} 

or

{% if entry.myField|length %}...{% endif %}

If the field is not defined in the field layout however, these may also return an error. In which case you might want to use Twig's 'is defined' first, before checking if the field is empty.

`{% if entry.myField is defined %}...{% endif %}`

In most cases, I just use {% if entry.myField %}...{% endif %}.

  • 3
    Not really related to the question but maybe this helps someone reading this great answer. You can get only those entries with non empty fields using a custom field parameter on the ElementCriteriaModel like so: {% set entries = craft.entries.myField(':notempty:') %}. – carlcs May 7 '15 at 7:21

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.