Andresch Serj
Andresch Serj

Reputation: 37448

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

Upvotes: 7

Views: 12176

Answers (2)

CodeSlave
CodeSlave

Reputation: 457

You can use "length" example:

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

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

Upvotes: 1

Andresch Serj
Andresch Serj

Reputation: 37448

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>

Upvotes: 21

Related Questions