Twig: actualiza la variable ubicada anteriormente en el código

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.

He aquí un ejemplo:

<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.

Gracias,

JB

preguntado el 30 de junio de 12 a las 15:06

Usually you do calculations like this not in your template (View) but your Model. You want to keep the programming part away from the template so that even designers may change the View part. -

Agreed. Normally I would want to keep them partitioned, but this one has a specific implementation, thus the quest to see if it can be solved through the template. -

1 Respuestas

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 %}

Respondido el 30 de junio de 12 a las 21:06

I'll just add that templates are not the right place for calculations. - jakub zalas

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.