2016-10-02 90 views
0

我有一个Account对象,它包含与newsbrief成员的一对多关系。在Twig中想要显示成员的数量。我知道我可以显示量用下面的代码:Can Twig可以用过滤器参数计算数组长度

{{ account.mailList|length }} 

只有邮件列表还包含不活动的成员。与这些成员他们的领域活跃是错误的。有没有办法将它们滤除?这种工作方式是否会减慢应用程序的运行速度?

+1

你可以写下你自己的树枝过滤器:http://symfony.com/doc/current/templating/twig_extension.html – Cerad

回答

0

可以在树枝用于循环:

{% set activeMailCount = 0 %} 
{% for mail in account.mailList if account.mailList.active %} 
    {% set activeMailCount = activeMailCount + 1 %} 
{% endfor %} 
2

你可以在返回账户实体创建一个方法活跃会员

// src/AppBundle/Entity/Account.php 
public function getActive() 
{ 
    $count = 0; 

    foreach($this->getMailList() as item) { 
     if (item->isActive()) { // Assuming the newsbrief members are entities 
      $count++   // with an $active property & isser(). 
     } 
    } 

    return $count; 
} 

,并呼吁从细枝:

{{ account.getActive() }} # or {{ account.active }}