switch statement in twig drupal 8

The Naga Tanker picture The Naga Tanker · Nov 5, 2016 · Viewed 17.5k times · Source

Does twig in drupal 8 have a switch case statement?

Something like:

{% set size = rows | length %}
{% switch rows %}
    {% case "1" %}
        {{ do something }}
    {% case "2" %}
        {{ do example }}
    {% case "3" %}
        {{ do that }}
    {% default %}
        <p>A font walks into a bar.</p>
        <p>The bartender says, “Hey, we don’t serve your type in here!”</p>
{% endswitch %}

I tried this:

 {% if size ==1 %}
values 1
{% elseif size ==2 %}
values 2
{% else %}
value not found
{% endif %}

But it seems its stucked on the first statement never goes to the second section/statement even when the value is 2

Answer

Alex Averdunk picture Alex Averdunk · Nov 3, 2018

I think there doesn't exist a Switch function in Symfony/Twig. You have to fall back on a standard

{% if condition %}
...
{% elseif condition2 %}
...
{% else %}
...
{% endif %}

Hope I could help..