【问题标题】:Symfony2 Twig Get Total Count for Child EntitySymfony2 Twig 获取子实体的总数
【发布时间】:2014-06-27 14:53:11
【问题描述】:

存在以下实体,农场、谷仓和动物。一个农场可以有很多谷仓,一个谷仓可以有很多动物。

在 TWIG 模板中显示农场时,还应显示动物的数量。

最好的方法是什么?

我创建了一个 TWIG 扩展程序,它可以让我轻松地显示谷仓的数量。

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

在我的模板中我会使用 {{ farm|totalField('getBarns') }},我可以轻松地扩展它来编写另一个自定义函数,如下所示:

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

虽然这可行,但有没有更好的方法,可以让它更通用吗?如果我想数动物的腿怎么办?或者一个谷仓有多少门,我每次都必须编写一个自定义的 TWIG 扩展。

【问题讨论】:

    标签: php symfony twig


    【解决方案1】:

    使用实体访问器:

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

    【讨论】:

    • 谢谢,这行得通。我希望可能有一个更清洁的解决方案。我想我会在 PHP 中计算动物并将值传递给模板。
    【解决方案2】:

    您正在寻找length filter

    当与数组一起使用时,长度将为您提供项目数。所以,如果你的数组是farm.barns,你可以使用{{ farm.barns|length }}

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-31
    • 2013-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 2016-11-11
    • 2013-07-31
    相关资源
    最近更新 更多