The switch statement replaces a series of if/else/elseif statements and makes the code more straightforward and readable.
For choice in control flow in Twig, we only have if
and its siblings else
and elseif
. However, if you are using Craft CMS, you also have access to an additional control flow option: switch
. Craft CMS’s implementation of switch
is custom and not part of the core Twig library.
But the switch
statement is common in most languages, especially those somewhat rooted in C. The switch
statement replaces a series of if
/else
/elseif
statements and makes the code more straightforward and readable.
An everyday use of the switch
statement in Craft CMS and Twig is outputting Matrix field data.
Let’s say we have a data set for a few online courses. Two of them are video-based, and one is an ebook. I want to present different options depending on the course type. The video course will have a preview, and the ebook will have a download sample. There could, potentially, be other layout issues we’d want to incorporate.
Of course, I could accomplish this with a series of if
statements, but it’s a bit more elegant to use switch
.
Here’s our data:
{% set materials = {
'CQ-CRAFT': {
'type': 'video',
'name': 'Up and Running with Craft 3',
'url': 'https://craftquest.io/courses/craft-3',
'videoId': '123456'
},
'CQ-TWIG': {
'type': 'video',
'name': 'Twig Templates in Craft',
'url': 'https://craftquest.io/courses/twig-templates',
'videoId': '123456'
},
'CQ-CRAFT-BOOK': {
'type': 'ebook',
'name': 'Up and Running with Craft CMS',
'url': 'https://craftquest.io/ebooks/craft-cms',
'sampleFile': 'https://craftquest.io/downloads/somefile.pdf'
}
}
%}
We could accomplish this like this:
{% for item in materials %}
{% if item.type == 'video' %}
{# something here #}
{% elseif item.type == 'ebook' %}
{# something else here #}
{% endif %}
{% endfor %}
But with many cases to go through, this could get difficult to manage. So it may look okay right now but using switch
is a cleaner approach.
And this is what our code would look like with switch
(I’ve added a bit more detail to the output code):
<dl>
{% for item in materials %}
<dt>
<h4>{{ item.name }}</h4>
</dt>
<dd>
<h5>Material Type: {{ item.type | upper }}</h5>
{% switch item.type %}
{% case 'video' %}
<p>Video Preview:
{{ item.videoId }}</p>
{% case 'ebook' %}
<p><a href="{{ item.sampleFile }}">Download Sample</a></p>
{% endswitch %}
</dd>
{% endfor %}
</dl>
The first thing we have to do is iterate over each of the items in the materials
array, and then on each of those items’ type, we can do with cases checking for the type and then outputting the markup or content specific to that type.
Now we have a much cleaner and more maintainable way to iterate over Matrix blocks while reacting to the different block types.
Watch our free video course to learn more about Craft CMS and Twig control flow to learn more about how to control how and when you output content in your Twig templates.