Symfony2 Twig Get Total Count for Child Entity

2019-02-27 12:42发布

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.

标签: php symfony twig
2条回答
祖国的老花朵
2楼-- · 2019-02-27 13:06

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 %}
查看更多
ら.Afraid
3楼-- · 2019-02-27 13:13

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

查看更多
登录 后发表回答