hous hous - 1 year ago 163
Twig Question

Get length of array with condition on attribute

I'd like if is it possibel to get length of array with condition on attribute without create another query in the controller.

public function pageAction()
{
$em = $this->getDoctrine()->getManager();
$pages = $em->getRepository('AppBundle:Page')->findAll();
return $this->render(':Frontend/includes:menu.html.twig', array(
'pages' => $pages
));
}


in the view

//number of all pages
{{ pages|length }} // output 15 (ok)


now is it possible to get the number of pages where page.activate == true from the same result returned in the controller ?

// number of page where page.activate == true
??

Answer Source

This should work hous:

{% set pageCount = 0 %}{# Sets variable #}
{% for p in pages %}
    {% if p.getActivate %}
        {% set pageCount = pageCount + 1 %}
    {% endif %}
{% endfor %}

<p>Activated Pages: {{ pageCount }}

Try it!