简体   繁体   English

Symfony2 Twig获取子实体的总数

[英]Symfony2 Twig Get Total Count for Child Entity

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. 在TWIG模板中显示农场时,还应显示动物数量。

What is the best way to do this? 做这个的最好方式是什么?

I have create a TWIG extension which allows me to easily show the number of barns. 我创建了一个TWIG扩展名,该扩展名使我可以轻松显示谷仓的数量。

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: 在我的模板中,我将使用{{farm | totalField('getBarns')}},可以很容易地扩展它以编写另一个自定义函数,如下所示:

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. 或一个谷仓有多少扇门,我每次都必须编写一个定制的TWIG扩展名。

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

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 }} 因此,如果您的数组是farm.barns,则只需使用{{ farm.barns|length }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM