Compare Value to String IF/FOR Statement

52 views Asked by At

I'm currently trying to compare the value of each saved Entity and organize the results into certain sections. I can't for the life of me find how to compare a variable to a string using twig. Everything I've tried error's except for the following code which instead of failing, just skips the IF's and shows the ELSE. I'm assuming I've got it all wrong but the Twig documentation has no mention of how to do it (I think) and I'm beginning to think I'm going about it all the wrong way. Maybe I should be doing it in the controller?

{% for product in entity.product %}
    {% if product.dish.DishCat == 'Starter' %} 
        <h3>Starter</h3>
        <p>{{ product.dish }}</p>
    {% elseif product.dish.Dishcat == 'Main'%}
        <h3>Main</h3>
        <p>{{ product.dish }}</p>
    {% elseif product.dish.Dishcat == 'Desert'%}
        <h3>Desert</h3>
        <p>{{ product.dish }}</p>
    {% else %} // Always just get's to here.
        <p> FAIL!</p>
        <p>{{product.dish.DishCat}} {{product.dish.id}}</p> //I print 'product.dish.DishCat' to ensure It's actually got a value which it does...
    {% endif %}
{% endfor %}

Result =

FAIL! Mains 2

FAIL! Starters 0

FAIL! Starters 1

FAIL! Deserts 3

FAIL! Mains 4

Any suggestion's very welcome.

1

There are 1 answers

1
George On BEST ANSWER

The results all end with an 's' while the conditional statements do not. Try:

{% for product in entity.product %}
    {% if product.dish.DishCat == 'Starters' %} 
        <h3>Starter</h3>
        <p>{{ product.dish }}</p>
    {% elseif product.dish.Dishcat == 'Mains'%}
        <h3>Main</h3>
       <p>{{ product.dish }}</p>
    {% elseif product.dish.Dishcat == 'Deserts'%}
        <h3>Desert</h3>
        <p>{{ product.dish }}</p>
    {% else %} // Always just get's to here.
        <p> FAIL!</p>
        <p>{{product.dish.DishCat}} {{product.dish.id}}</p>
        //I print 'product.dish.DishCat' to ensure It's actually got a value which it does...
   {% endif %}
{% endfor %

I think you should try to fix the variables and not let all of them end with a 's'.