存在以下实体:农场、谷仓和动物。一个农场可以有很多谷仓,一个谷仓可以有很多动物。
在 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 扩展。
使用实体访问器:
{% 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 %}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)