How do I return the highest and lowest value within a loop by using Twig?

Asked

Viewed 78 times

0

I make a list of some products and would need to return the largest and lowest value of products without using max and min in SQL query. I tried to use for example the function max() from Twig, but returns some errors. Below is what I did and the error that is happening:

Code:

{% for product in produtos %}
        {% set maxValue = max(product.valor)%}
        Valor--->>{{maxValue}}
{% endfor %}

Error:

An exception has been thrown during the rendering of a template ("max() [<a href='function.max'>function.max</a>]: When only one parameter is given, it must be an array")
  • The max problem is even easy to solve with {% set maxValue = max(product.valor, maxValue)%} or something similar, but it may not be enough for your logic.

  • @Marcosregis didn’t work out. I need to return this value to use in a custom price filter where the maximum value would be the highest value of the products listed. I am not using max() in the SQL query because when performing the search I pass other parameters such as product characteristics and for me to make a select max(product.value) from product I would have to do two different searches but passing the conditions of the main search of the products listing.

  • but it was not stored in maxValue??

  • @Marcosregis, I did exactly as you showed in the example but it didn’t work

  • 1

    that should work {% set maxValue = 0 %} &#xA;{% for product in produtos %}&#xA; {% set maxValue = max(product.valor, maxValue) %}&#xA;{% endfor %}&#xA;{{ maxValue }}

  • Now it worked. I think I ended up typing something wrong. Thanks Dude!

  • 1

    I put as an answer.

Show 2 more comments

1 answer

1


Try it like this

{% set maxValue = 0 %} 
{% for product in produtos %} 
{% set maxValue = max(product.valor, maxValue) %} 
{% endfor %} 
{{ maxValue }}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.