2
votes

I am new in symfony, trying to study the conditional statement. Having difficulty in adding the sum of all in my for loop.

Question: How can I fix the error "Unexpected token "operator" of value "=" ("end of print statement" expected) and may I know what is the cause of having this error?(for future reference)

My twig file

<!DOCTYPE html>
<html>
<head>
    <title>{{ title }} </title>
</head>
<body>
    {% set number1 = 2 %}
    {% set number2 = 1 %}
    {% set total = 0 %}

    {# If-else condition#}

    <!-- {% if number1 > number2 %}
        {{ "Number 1 is greater than to number 2"}}

    {% else %}

        {{ "Number 2 is greater than to number 1"}}
    {% endif %} -->

    {# If-elseif-else condition #}
<!-- 
    {% if number1 == number2 %}
        {{ "Number 1 number 2 is equal"}}

    {% elseif number1 > number2 %}
        {{ "Number 1 is greater than to number 2"}}

    {% else %}

        {{ "Number 2 is greater than to number 1"}}
    {% endif %} -->

    {# For loop #}
<!-- 
    {% for i in 1..10 %}
        {{ i }}
    {% endfor %} -->

    {# For loop getting the sum #}

    {% for i in 1..10 %}
        {{ total = total + i }}
    {% endfor %}

</body>
</html>
1

1 Answers

7
votes

+= is not a valid twig operator. This is what is causing the error. If you need to increment the variable you will need to do it in a separate statement.

{{ total += i }} should be {% set total = total + i %} {{ total }}