I'm building an help centre for an application and I want to be able to display the number of topics within a specific category. At the moment, this is what I have:
{% for cat in cats %}
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="accordion" data-toggle="collapse" data-parent="#helpcategories" href="#category{{cat.id}}">
{{cat.category}}
{% for top in tops %}
{% if top.category == cat.id %}
<span class="badge pull-right">
{{ tops|length }}
</span>
{% endif %}
{% endfor %}
</a>
</h4>
</div>
<div id="category{{cat.id}}" class="panel-collapse collapse">
<div class="panel-body">
<ul class="nav nav-pills nav-stacked">
{% for top in tops %}
{% if top.category == cat.id %}
<li><a href="#" class="list-group-item">{{top.title}}</a></li>
{% endif %}
{% endfor %}
</ul>
</div>
</div>
</div>
{% endfor %}
As you can see, I use Twig to sort out the topics in to their respective categories. As you can also see, in the area that I want to display the number of topics within a category I am using {{tops|length}}. However, this returns the number of topics in total, not per category.
How can I get Twig to count the number of times a topic appears in a category?