Search code examples
twigopencart-3

if else not working in opencart 3 twig file


i'm trying to integrate the following code in opencart 3,but i don't know why my code id not executing?i'm new to twig.Please help me to fix this issue.

{% for product in products %}
 {{ product.total}}  
 {% set my_total = product.total|replace({'AED': '', ',': ''}) %}
 {{ my_total }}
  {% endfor %}
{% if my_total >= 500.00 %}
{% set randomPassword = [] %}
{% set alpha = 'abcdefghijklmnopqrstuvwxyz' %}
{% set numbers = '0123456789' %}
{% for i in 1..10 %}
{% set randomCharacter = random(alpha ~ alpha|upper ~ numbers ~ '-_') %}
{% set randomPassword = randomPassword|merge([randomCharacter]) %}
{% endfor %}
{% set randomPassword = randomPassword|join %}
{{ order_id }}{{ randomPassword }}
{% else %}
(text)
{% endif %}

Solution

  • Variables defined inside a for-loop are only known inside such loop. As you are trying to access my_total outside the loop u'd need to define it outside the loop, e.g.

    {% set my_total = 0 %} {# <--- outside the loop #}
    
    {% for product in products %}
        {% set my_total = my_total + product.total|replace({'AED': '', ',': ''}) %}
    {% endfor %}
    
    {% if my_total >= 500.00 %} {# <--- still accessible #}
    
        {% set randomPassword = [] %}
        {% set alpha = 'abcdefghijklmnopqrstuvwxyz' %}
        {% set numbers = '0123456789' %}
    
        {% for i in 1..10 %}
            {% set randomCharacter = random(alpha ~ alpha|upper ~ numbers ~ '-_') %}
            {% set randomPassword = randomPassword|merge([randomCharacter]) %}
        {% endfor %}
    
        {% set randomPassword = randomPassword|join %}
        {{ order_id }}{{ randomPassword }}
    {% else %}
        (text)
    {% endif %}
    

    demo


    note: You should enable debug mode in order to see twig errors, when running your code you clearly get the following error

    Variable "my_total" does not exist.