Symfony2 Twig Get Total Count for Child Entity

2019-02-27 12:50发布

问题:

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.

回答1:

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 %}


回答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 }}



标签: php symfony twig