Search code examples
twigopencart-3

Opencart 3 TWIG: how to use AND operator


I'm trying to use the "AND" operator in TWIG in Opencart 3 and it doesn't work. Please tell me what I'm doing wrong.

I have some product attributes. And I want to make a condition that if two of the attribute with a specific ID are there, then the condition is met.

{% for attribute_group in attribute_groups %}
    {% for attribute in attribute_group.attribute %}
        {% if attribute.attribute_id == 2 and attribute.attribute_id == 3 %}
            First condition
        {% elseif attribute.attribute_id == 2 %}
            Second condition
        {% elseif attribute.attribute_id == 3 %}
            Third condition
        {% else %}
        {% endif %}
    {% endfor %}
{% endfor %

Here is text example:

if there is an attribute with ID equal 2 and an attribute with ID equal 3 then write "Floor/Number of floors". 
if there is an attribute with ID equal 2 only then write "Floor"
if there is an attribute with ID equal 3 only then write "Numbers of floors".

Solution

  • Something can't be both X and Y at the same time. Furthermore this is something I'd advice you to test in the controller and not in the view.

    Anyway if you wanted to do this in the view you will need to track of the found attributes. You could do this with two booleans or just add a counter.

    {% set cnt = 0 %}
    {% for attribute_group in attribute_groups %}
        {% for attribute in attribute_group.attribute %}
            {% if attribute.attribute_id == 2 or attribute.attribute_id == 3 %}
                {% set cnt = cnt + 1 %}
            {% endif %}
        {% endfor %}
    {% endfor %}
    
    {% if cnt == 2 %}
        {# do something #}
    {% endif %}
    

    You can simplify the if by using the test in

    {% if attribute.attribute_id in [2, 3,] %}
    

    Update of my answer because OP changed the requirements of the question

    {% set words = [] %}
    {% for attribute_group in attribute_groups %}
        {% for attribute in attribute_group.attribute %}
            {% if attribute.attribute_id == 2  %}
                {% set words = words|merge(['Floor',]) %}
            {% elseif attribute.attribute_id == 3  %}
                {% set words = words|merge(['Numbers of floors',]) %}
            {% endif %}
        {% endfor %}
    {% endfor %}
    
    {% if words|default  %}
        {{ words|join('/') }}
    {% endif %}
    

    demo