title: Symfony2 Twig Get Total Count for Child Entity
body: <p>The following entities exist, Farm, Barn and Animals. A Farm can have many Barns and a Barn many Animals.</p>
  
  <p>When displaying a Farm in a TWIG template the number of Animals should be shown as well.</p>
  
  <p>What is the best way to do this?</p>
  
  <p>I have create a TWIG extension which allows me to easily show the number of barns.</p>
  
  <pre><code>public function totalFieldFilter($data, $getField='getTotal') {
      $total = count($data-&gt;$getField());
      return $total;
  }
  </code></pre>
  
  <p>In my template I would use {{ farm|totalField('getBarns') }}, I could easily extend this to write another custom function like so:</p>
  
  <pre><code>public function totalFieldFilter($farm) {
      $total = 0;
      foreach($farm-&gt;getBarns() AS $barn) {
          $total += count($barn-&gt;getAniamls());
      }
      return $total;
  }
  </code></pre>
  
  <p>Although this would work, is there a better way and can it be made more generic? What if I wanted to count Legs on Animals? Or how many Doors a Barn has, I would have to write a custom TWIG extension each time.</p>