3

I'm not sure what's wrong with this original markup:

Conditional One (doesn't work)

{% if entry.metaTitle is defined %}
  {{ entry.metaTitle }}
{% elseif title is defined %}
  {{ title }}
{% else %}
  {{ siteName }}
{% endif %}

This works but seems a bit much for some simple checks:

Conditional Two (does work)

{% if entry.metaTitle is defined %}
  {{ entry.metaTitle }}
{% endif %}
{% if (title is defined) and (entry.metaTitle is empty) %}
  {{ title }}
{% endif %}
{% if (title is empty) and (entry.metaTitle is empty) %}
  {{ siteName }}
{% endif %}

As you can see I'm checking first if metaTitle is set, then title then finally fallback to siteName. Entering data for the first two return results, but not sure why if metaTitle and title are empty why siteName doesn't return in the first conditional

#

Update based on Aaron's answer:

Tried this too:

{% if (entry.metaTitle is defined) and (entry.metaTitle is empty)  %}
  {{ entry.metaTitle }}
{% elseif title is defined %}
  {{ title }}
{% else %}
  {{ siteName }}
{% endif %}

#

Also tried this, Aaron was missing a ( in his answer :)

{% if (entry.metaTitle is defined) and (entry.metaTitle != '')  %}
  {{ entry.metaTitle }}
{% elseif title is defined %}
  {{ title }}
{% else %}
  {{ siteName }}
{% endif %}

But that doesn't work either with the same initial results.

Mark Busnelli Jr
  • 926
  • 7
  • 18

3 Answers3

9

This looks like a situation where you might get away with just using Twig's default filter:

{{ entry.metaTitle|default(title|default(siteName)) }}

It works even with undefined or empty strings, and methods that don't exist on objects that might not be defined themselves.

Mike Pepper
  • 4,391
  • 17
  • 26
4

From what I can tell, the problem is in the first line of the conditional, {% if entry.metaTitle is defined %}.

If you are on an entry, entry.metaTitle will be defined as part of the entry model (even if it is empty), so your conditional returns true.

Give this a try:

{% if (entry.metaTitle is defined) and (entry.metaTitle != '')  %}
  {{ entry.metaTitle }}
{% elseif title is defined %}
  {{ title }}
{% else %}
  {{ siteName }}
{% endif %}
Aaron Berkowitz
  • 3,819
  • 10
  • 20
2

I think this is where the problem is...

...
{% elseif title is defined %}
    {{ title }}
...

I'd be willing to wager that title is always defined. Remember, there is a difference between being defined vs. being empty.

Assuming your title is defined, but set to null or an empty string, you'll still be triggering this part of the if/else statement. But when you render the {{ title }} value, it will render as an empty string.

As a solution, try writing your second conditional like this:

...
{% elseif (title is defined) and (title is not empty) %}
    {{ title }}
...
Lindsey D
  • 23,974
  • 5
  • 53
  • 110