Symfony2:数组 [twig] 中不存在键
Symfony2: Key no exists in array [twig]
我想显示数组中元素的数量,但是我遇到了这个问题
Key "idTipoFarmaco" for array with keys "0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12" does not exist in
FarmacoBundle:Default:chartTipos.html.twig at line 17
模板
{% 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
));
}
将您的模板更新为:
{% block artic %}
{{ entities|length }}
{% endblock %}
根据您对 Jonathan 的评论(您在评论中解释说您想要对实体数组中满足特定要求的元素进行计数)我会说您必须在获取数组长度之前应用过滤器。
请参阅the Symfony documentation了解如何创建自定义过滤器。
首先创建一个 Twig 扩展 class:
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 %}
我想显示数组中元素的数量,但是我遇到了这个问题
Key "idTipoFarmaco" for array with keys "0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12" does not exist in FarmacoBundle:Default:chartTipos.html.twig at line 17
模板
{% 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
));
}
将您的模板更新为:
{% block artic %}
{{ entities|length }}
{% endblock %}
根据您对 Jonathan 的评论(您在评论中解释说您想要对实体数组中满足特定要求的元素进行计数)我会说您必须在获取数组长度之前应用过滤器。
请参阅the Symfony documentation了解如何创建自定义过滤器。
首先创建一个 Twig 扩展 class:
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 %}