When checking if a field has content or not in my templates I usually write something along the lines of:

{% if entry.fieldHandle|length %}
    <h1>{{ entry.fieldHandle }}</h1> 
{% endif %}

Writing the same code without the |length filter does also work, so can I just exclude the use of the filter from my code altogether? Are there any caveats with not using the filter?

As an aside, I am aware that |length does have its uses. You can use this to check the exact value of something, etc etc.

This question was more suited for a simple yes/no check to see if a field has any content and outputting something if it does.

Another example of the |length filter in my code would be something like:

{% set homepageServices = craft.entries.section('services').type('serviceGroup').level(1) %}
{% if homepageServices|length %}
    <p>Output the services here</p>
{% endif %}

Would removing |length (which does work at the moment) cause me any headaches down the line?


You can probably get away with removing |length for most conditionals that check for the existence of content in a custom field and just check on entry.fieldHandle instead.

One exception to this would be for lightswitch fields, which always return true for a |length check, but return true or false when checking on entry.fieldHandle depending on whether the lightswitch is on or off.

StraightUpCraft has a great article on Testing if something exists and another on How to check if a variable or value exists using Twig, which cover a multitude of cases and ways of accessing variables using Twig.


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.