我想显示数组中元素的数量,但我有这个问题
Key" idTipoFarmaco"对于带有键的数组" 0,1,2,3,4,5,6,7,8,9, 10,11,12和#34;在...中不存在 FarmacoBundle:默认:第17行的chartTipos.html.twig
模板
{% block artic %}
{{ entities.idTipoFarmaco.nombreFarmaco|length}}
{% endblock %}
功能
public function chartTiposFAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('::Entity')->findAll();
return $this->render('::chartTipos.html.twig', array(
'entities' => $entities
));
}
答案 0 :(得分:2)
基于你对Jonathan的评论(你在其中解释你想要计算实体数组中符合某些要求的元素),我会说你必须在获得数组的长度之前应用一个过滤器。
有关如何创建自定义过滤器的信息,请参阅the Symfony documentation。
首先创建一个Twig扩展类:
namespace Foo\BarBundle\Twig;
use Doctrine\Common\Collections\Collection;
class YourTwigFiltersExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('filterType', array($this, 'filterType')),
);
}
public function filterType(Collection $entities, $type)
{
return $entities->filter(function ($e) use ($type) {
return $e->getType() == $type; // Replace this by your own check.
});
}
public function getName()
{
return 'your_twig_filters';
}
}
然后将您的扩展名注册为services.yml(或您的xml)中的服务:
foobar.twig.filters_extension:
class: Foo\BarBundle\Twig\YourTwigFiltersExtension
public: false
tags:
- { name: twig.extension }
在模板中使用如下:
{% block artic %}
{{ entities|filterType('dog')|length }}
{% endblock %}
答案 1 :(得分:0)
将您的模板更新为:
{% block artic %}
{{ entities|length }}
{% endblock %}