1

This question already has an answer here:

I got a Twig switch in a template like:

{% switch bodyClass %}

    {% case 'A' %}
        ...

    {% case 'B' %}
        ...

    {% default %}
        ...

{% endswitch %}

I would like to add another possible value for the first case.
So I would have case 'A' or 'C'.

Is it possible in Twig syntax?

=================================
EDIT CRAFT BUG ?
OK lets try to rephrase, sorry for my english not easy to explain for me sometimes :)
So when the or syntax is added, then the 2nd and 3rd cases B or default (after 'A1' or 'A2' case) are never reached anymore.
The switch always say TRUE to 1st case (even if it is wrong...).

{% switch bodyClass %}

    {% case 'A1' or 'A2' %}
        ...

    {% case 'B' %}
        ...

    {% default %}
        ...

{% endswitch %}

marked as duplicate by carlcs, Lindsey D Aug 28 '15 at 19:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

This currently isn't a supported syntax for the Twig switch statement.

Craft will take that line and compile it down to:

case ("A1" || "A2"):

Which will always evaluate to true, which is why you always get the first result.

In order for it to work, it would need to be either:

case "A1":
case "A2":

To take advantage of PHP's fall-through support or the more ugly:

case ($context["bodyClass"] == "A1" || $context["bodyClass"] == "A2")
  • Yeah I tried it just before your answer by intuition and it worked ! Cool :D – migswd Aug 20 '15 at 17:32
  • Hey Brad I think I got a Craft bug here : now my template only show first case (A or C), even when it is false. – migswd Aug 21 '15 at 18:54
  • It worked yesterday, but today it doesn't? – Brad Bell Aug 21 '15 at 19:07
  • Because I just checked case A or C yesterday. I did not check the other cases. Thats why I did not see it... I really double checked the value of bodyclass before the switch. And it displays B. But the switch return A or C case. – migswd Aug 21 '15 at 19:24
  • Not sure I'm following... what's the value of bodyClass that causes B to be displayed? – Brad Bell Aug 21 '15 at 19:37
1

The switch tag is a Twig extension that comes as part of Craft. From looking at the code for the Switch_TokenParser in the Craft full class reference it looks as if it is expecting an expression after case so you should be able to put in any valid Twig expression that equates to true or false.

Not the answer you're looking for? Browse other questions tagged or ask your own question.