jbsound
jbsound

Reputation: 787

Twig: Update variable located earlier in code

I need to show a value at the top of a page, which needs to be updated after I have run some Twig loops in the middle of the page.

Here's an example:

<div>Total Amount: {{ totalAmount }}</div>
{% for product in products %}
    {% set totalAmount = totalAmount + product.amount %}
{% endfor %}

I could compute the value in the Symfony controller, but there are certain reasons why I would prefer doing this in the Twig template.

Is the above possible with Twig? I'm sure the Twig code is executed sequentially and I may have to find a different solution. But I'd like to see if anyone has any suggestions.

Thanks,

JB

Upvotes: 2

Views: 9426

Answers (1)

Jakub Zalas
Jakub Zalas

Reputation: 36191

Use blocks.

In your main template (layout):

<div>Total Amount: {% block totalAmount %}{% endblock %}</div>

In your child template:

{% for product in products %}
    {% set totalAmount = totalAmount + product.amount %}
{% endfor %}

{% block totalAmount %}{{ totalAmount }}{% endblock %}

Upvotes: 4

Related Questions