1

I'm trying to create a switch statement for a single entry event template that has various entry fields associated with it (description, contact, location, etc.) from an Events Channel I have. Rather than using a bunch of IF's to display only those fields that have been populated, I'm trying to use a switch statement instead, but I can't get this to work when I based the switch on the 'entry.type." I'm trying to something like this, but it's not working. Any help would be appreciated!

{% switch entry.type %}
{% case 'contact' %}
    {{ entry.contact }}
{% case 'location' %}
    {{ entry.location }}
{% endswitch %}
1

It's a little unclear what you need to achieve here –

If your entries' entry type handles actually are 'contact' and 'location', the above code should work; which means that you've got an error somewhere that isn't really possible to figure out based on your description – e.g. the entry type handle is actually contacts, and not contact, or something like that.

One thing you might try, is to simply print the entry.type variable in a template, to see if it contains what you expect it to contain:

{{ entry.type }}

On the other hand, if your issue is simply that some entries have a contact field populated and others have a location field populated, you can't really use a {% switch %} statement in any sensible manner for that – though a plain old {% if %} would do it:

{% if entry.contact %}
    {{ entry.contact }}
{% elseif entry.location %}
    {{ entry.location }}
{% endif %}
  • Thanks, Mat! I was basically trying to do what you described, which is to use a switch statement rather than a bunch of IF statements. Good to know that wouldn't work. I was figuring using a switch was perhaps a better, less taxing way to set up all my fields, check to see if they're populated, and then have them print if the field is populated rathering than using a bunch of IFs. Thanks again! – user3092 Sep 12 '17 at 21:28
  • No worries. In terms of less taxin, I really doubt you'll find any difference in performance in switch statements vs. regular if conditionals, one way or the other – switch statements can offer a more clear/readable syntax in some situations (and I don't think yours is a plausible use case for them), but that's about it :) – Mats Mikkel Rummelhoff Sep 12 '17 at 21:30

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.