Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch statement in twig drupal 8

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

like image 984
The Naga Tanker Avatar asked Nov 05 '16 11:11

The Naga Tanker


People also ask

How do I override a Twig template in Drupal 8?

Overriding templatesLocate the template you want to override. Copy the template file from its core location into your theme folder. Rename the template according to the naming conventions in order to target a more specific subset of areas where the template is used. Modify the template according to your wish.

How do I use Twig extension in Drupal 8?

To start with it first, we need to create a module. 1.) Create a new module inside: /modules/custom/ directory inside your drupal project. description: 'Provides Twig Extension that process the Alt tag of any given image.

How do I use Twig template in Drupal?

Once you copy a template file into your theme and clear the cache, Drupal will start using your instance of the template file instead of the base version. You can find out what templates are in use for any part of the page by using the Twig debugging tools.


2 Answers

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..

like image 85
Alex Averdunk Avatar answered Oct 22 '22 19:10

Alex Averdunk


I was also looking to do a "switch statement" for my view template for Drupal 8, but I couldn't get it to work. I had the following:

{% set rowsLength = rows|length %}
{% switch rowsLength %}
    {% case 1 %}
        ...
    {% case 2 %}
        ...
    {% case 0 %}
        ...
{% endswitch %}

But when uploaded it just gave didn't render and put at that message of "something is wrong". So I ended up using the following "if" statement:

{% set rowsLength = rows|length %}
{% if rowsLength > 0 and rowsLength < 4  %}
    {% set nav_size = "small-carousel" %}
{% elseif rowsLength > 4 and rowsLength < 6 %}
    {% set nav_size = "medium-carousel" %}
{% else %}
    {% set nav_size = "" %}
{% endif %}

Hope it helps.

like image 28
Chayemor Avatar answered Oct 22 '22 21:10

Chayemor