2

The following entities exist, Farm, Barn and Animals. A Farm can have many Barns and a Barn many Animals.

When displaying a Farm in a TWIG template the number of Animals should be shown as well.

What is the best way to do this?

I have create a TWIG extension which allows me to easily show the number of barns.

public function totalFieldFilter($data, $getField='getTotal') {
    $total = count($data->$getField());
    return $total;
}

In my template I would use {{ farm|totalField('getBarns') }}, I could easily extend this to write another custom function like so:

public function totalFieldFilter($farm) {
    $total = 0;
    foreach($farm->getBarns() AS $barn) {
        $total += count($barn->getAniamls());
    }
    return $total;
}

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.

lookbadgers
  • 988
  • 9
  • 31

2 Answers2

3

Use Entity accessors :

{% for farm in farms %}

  {{ farm.name }}

  {% set barns = farm.getBarns() %}

  Barns count = {{ barns|length }}

  {% for barn in barns %}

    {% set animals = barn.getAnimals() %}

    {{ barn.name }} animals count : {{ animals|length }}

  {% endfor %}

{% endfor %}
David Jacquel
  • 51,670
  • 6
  • 121
  • 147
  • Thanks, that works. I was hoping there might be a cleaner solution. I think I will count the animals in PHP and pass the value to the template. – lookbadgers Jun 27 '14 at 16:57
2

You are looking for the length filter

When used with an array, length will give you the number of items. So, if your array is farm.barns, you can just use {{ farm.barns|length }}

Community
  • 1
  • 1
MrGlass
  • 9,094
  • 17
  • 64
  • 89
  • Thanks, how would you use that to get the number of animals? {{farm.barns.animals.length}} obviously won't work. – lookbadgers Jun 27 '14 at 15:37
  • Have a look to the [Twig Documentation for the `length` filter](http://twig.sensiolabs.org/doc/filters/length.html). – Ralf Hertsch Jun 27 '14 at 15:43