Problem with IF conditional not working I have 2 sections, events and activities, that share many fields. But activities doesn't have an eventLevel field as there isn't a level. eventLevel is a radio fieldtype. So I want to insert the eventLevel when it exists and if it doesn't just insert the text "Activity". I've tried various tests on if eventLevel is defined, is null, and length. If there is an eventLevel it displays, but if it's an activity I end up with an empty cell.

{% set events = craft.entries.find({section:'events,activities', eventDate : "&gt;= " ~ now.w3cDate() , order:'eventDate'}) %}
{% if events %}
    {% for entry in events %}
    &lt;tr&gt;
        &lt;td class="col-date"&gt;{{ entry.eventDate.format('D j M') }}&lt;/td&gt;
        &lt;td&gt;&lt;a href="{{ entry.url }}" title="More info about {{ entry.eventName }}"&gt;{{ entry.eventName }}&lt;/a&gt;&lt;/td&gt;
        &lt;td&gt;{{ entry.nearestTown }}&lt;/td&gt;
        &lt;td&gt;{% if entry.eventLevel is defined %}{{ entry.eventLevel }}{% else %}Activity{% endif %}&lt;/td&gt;
    &lt;/tr&gt;
    {% endfor %}
{% endif %}


I've also tried the twig default filter with the same result:

{{ entry.eventLevel|default('Activity') }}
To test if a field exists, you'll have to use brackets notation, i.e.

{% if entry['eventLevel'] is defined %}
   ...
{% endif %}


When the field exists, but there isn't a selected option, the Radio FieldType returns an empty string, so you also need to test for entry.eventLevel != ''.

Putting it together, I believe a ternary conditional would perhaps be the most succinct solution in your particular case:

&lt;td&gt;{{ entry['eventLevel'] is defined and entry.eventLevel != '' ? entry.eventLevel : 'Activity' }}&lt;/td&gt;


What the above does is to first check if the entry has a property 'eventLevel' – the brackets notation is needed here, to avoid Twig throwing an exception if the entry variable doesn't have the property – before checking if the attribute's value is not an empty string. If both of those statements evaluate to true, then the attribute's value is printed; if not, the string Activity outputs.

This is a bit beside the point, but if you're wondering about the syntax here, the so called ternary operator (e.g. {{ variable ? 'yes' : 'no' }}) is just a kind of a short-hand way to write conditionals. Ternary operators are supported in many programming languages (including JavaScript and PHP).

If you wanted to, you could write out the full conditional and it would work exactly the same:

&lt;td&gt;
    {% if entry['eventLevel'] is defined and entry.eventLevel != '' %}
       {{ entry.eventLevel }}
    {% else %}
       Activity
    {% endif %}
&lt;/td&gt;


I'd argue that a ternary operator is more readable, shorter and also makes it easier to deal with potential whitespace issues etc. when inlined in markup like this, though.