7

With dev mode on, I'm getting a warning there is no entry.title, which I know about already because that's what I'm testing for:

{% if entry.title | length == 0 %}
    {% set entry = craft.entries.section('sectionname').slug(craft.request.segment(2)).first() %}
{% endif %}

Is there a way to test for a variable without dev mode triggering this notice?

12

I've had luck using "is defined" before using other logic operators.

This should do it:

{% if entry.title is defined and entry.title | length == 0 %}
    {% set entry = craft.entries.section('sectionname').slug(craft.request.segment(2)).first() %}
{% endif %}
  • 2
    I think you want to set entry to the new value if entry.title is not defined or is 0 length. Which is not what this code does. – Marion Newlevant Jun 27 '14 at 5:36
  • You're right. I ended up using something slightly different in practice. – Clive Portman Jun 27 '14 at 14:01
5

If you want to set entry to a new value if entry.title is undefined or 0 length, try this:

{% if !(entry is defined and entry.title is defined and entry.title|length) %}
    {% set entry = craft.entries.section('sectionname').slug(craft.request.segment(2)).first() %}
{% endif %}
3

Since Craft 2.6 you can do this cleanly with the ?? null-coalescing operator:

{% if not (entry.title ?? false) %}
  ...

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.