5
{% if entry.fieldHandle %}
  {{ entry.fieldHandle}}
{% else %}
  {{ global.fieldHandle}}
{% endif %}

Doesn't seem to be rendering for me. The entry field shows up when it's true, but the global field doesn't in the cases it needs to.

carlcs
  • 36,220
  • 5
  • 62
  • 139
lealea
  • 605
  • 1
  • 4
  • 15

2 Answers2

7

The reason it wasn't rendering is because my original entry field is an Entries Field (see templating examples in the docs). The relationship fieldtypes (Entries, Assets, Users) require that you include the length filter in your conditional like so:

{% if entry.fieldHandle |length  %}
  {{ entry.fieldHandle}}
{% else %}
  {{ global.fieldHandle}}
{% endif %}

Thanks to Keith Mancuso @keithmancuso for the fix!

lealea
  • 605
  • 1
  • 4
  • 15
2

For a relationship field you should use the length filter:

{% if entry.fieldHandle|length  %}

Or the more efficient total function to get and check against the total number of elements that match the criteria:

{% if entry.fieldHandle.total  %}

A more detailed answer on how to test for empty fieldtypes is here: https://craftcms.stackexchange.com/a/842/9

Note: this answer was edited based on clarification of the question as well as the comments below

Ben Croker
  • 7,341
  • 26
  • 55
  • Hey Ben, at one point I thought the entry variable alone {% if entry.fieldHandle %} was the same as {% if entry.fieldHandle is not empty %} but that doesn't seem to be the case in the way it behaves. Do you know what the default behavior of {% if entry.fieldHandle %} equates to in Twig? – Ben Parizek Jul 08 '14 at 23:47
  • i thought i had a grasp on the difference but after reviewing the docs and testing some things i am now unable to find any. i've left a comment for the original question to try to get to the bottom of why the code did not work. – Ben Croker Jul 09 '14 at 00:20
  • @BenCroker I think a question to investigate the difference between {% if entry.fieldHandle %} and {% if entry.fieldHandle is not empty %} would be pretty stellar. I'd post it, but then I'd feel vaguely guilty since you Bens brought it up. – Matt Stein Jul 09 '14 at 16:46
  • i think that would be classified as a twig question rather than craft, and frankly i don't think there is a difference in functionality, maybe use case though. – Ben Croker Jul 09 '14 at 20:26
  • 1
    {% if entry.fieldHandle %} is Craft specific and depends on the type of field. See Brandon's comment on g+. – carlcs Jul 09 '14 at 22:28
  • 2
    @BenCroker Here’s a full breakdown of how to test for whether each field type is empty: http://craftcms.stackexchange.com/a/842/9 – Brandon Kelly Jul 09 '14 at 23:53
  • thanks guys! brandon, are you still considering adding the hasValue function to fieldtypes? – Ben Croker Jul 10 '14 at 07:44