switch

The switch statement allows you to compare the value of a variable with multiple possible values and execute some code or output content depending on what the value is.

It is an alternative to using {% if %}{% elseif %}{% else %}{% endif %} statements.

Below is a simple example.

{% set value = 'value2' %}
{% switch value %}
    {% case 'value1' %}
        <p>value is "value1"</p>
    {% case 'value2' %}
        <p>value is "value2"</p>
    {% case 'value3' %}
    {% case 'value4' %}
        <p>value is "value3" or "value4"</p>
    {% default %}
        <p>value is something else</p>
{% endswitch %}

There is no need for break statements as each matching cases are automatically broken out of.

Switch statements support the {% default %} block to handle values that don't match any of the cases. It should be placed after all of the other cases.

Beginner's guide to cases

Each case should only contain the value the variable should be matched against. Like switch statements in other programming languages, you can't do other comparisons with the value. For example, the following IS NOT allowed.

{% case variable > 3 %}

The above will NOT work.

Essentially switch statements checks to see if each case value equals the variable in the switch statement.

Once a matching case is found the code after the case is processed and no more cases are tested.

Empty cases

If you do not have any code in between cases then they are essentially treated like OR comparisons. A break does not happen until the next case that has any code to execute.

In the example below the <p>value is "value3" or "value4"</p> output will show if the value variable equals "value3" or "value4"

{% set value = 'value2' %}
{% switch value %}
    {% case 'value1' %}
        <p>value is "value1"</p>
    {% case 'value2' %}
        <p>value is "value2"</p>
    {% case 'value3' %}
    {% case 'value4' %}
        <p>value is "value3" or "value4"</p>
    {% default %}
        <p>value is something else</p>
{% endswitch %}

Switch statements within loops

Switch statements work within for loops and all of the loop variables are available inside of the {% switch %} and {% case %} tags.

{% set values = ['A', 'B', 'C', 'D', 'E'] %}
{% for val in values %}
    <p>{{ val }}</p>
    {% switch val %}
        {% case 'A' %}
            <p>val is "A" at loop index {{ loop.index }}</p>
        {% case 'B' %}
            <p>val is "B" at loop index {{ loop.index }}</p>
        {% case 'C' %}
        {% case 'D' %}
            <p>val is "C" or "D" at loop index {{ loop.index }}</p>
        {% default %}
            <p>val is something else. It's "{{ val }}"</p>
    {% endswitch %}
{% endfor %}

< Back to the list of tags