Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2.1: count doctrine collection in twig template

I have a doctrine entity that has a collection of entities (children). Now i want to count the entities and print out the count. Something like this:

<div class="item">
 <h1>{{ object.name }}</h1>
 <div class="childrenCount">children {% count (object.children) %}</div>
</div>

I found some examples which didn't work (like using a "count" filter which resulted in a "filter not found" error).

like image 548
Andresch Serj Avatar asked Nov 23 '12 11:11

Andresch Serj


2 Answers

As found here, with doctrine there is the option to use the "count" method when handling a doctrine collection. Otherwise you can use the "length" Filter.

Example Code:

<ul class="summary">
  <li> {{ object.children | length }}</li>
  <!-- or, use the count method of doctrine collections directly -->
  <li> {{ object.children.count }}</li>
</ul>
like image 108
Andresch Serj Avatar answered Sep 22 '22 06:09

Andresch Serj


You can use "length" example:

{% if users|length > 10 %}
...
{% endif %}

See documentation: http://twig.sensiolabs.org/doc/filters/length.html

like image 35
CodeSlave Avatar answered Sep 22 '22 06:09

CodeSlave