Php 从字符串-Twig/Symfony访问子实体属性
如何访问Php 从字符串-Twig/Symfony访问子实体属性,php,symfony,twig,Php,Symfony,Twig,如何访问twig中的子实体属性值。例如: 我是沃克林: {% for entity in array %} {{ entity.child.child.prop1 }} {% endfor %} 我习惯将s字符串作为param传递,以获得相同的结果: {% for entity in array %} {{ attribute(entity, "child.child.prop1") }} {% endfor %} 但我得到了一个错误: 对象“CustomBundle\Ent
twig
中的子实体属性值。例如:
我是沃克林:
{% for entity in array %}
{{ entity.child.child.prop1 }}
{% endfor %}
我习惯将s字符串作为param传递,以获得相同的结果:
{% for entity in array %}
{{ attribute(entity, "child.child.prop1") }}
{% endfor %}
但我得到了一个错误:
对象“CustomBundle\Entity\Entity1”的方法“child.child.prop1”
不存在
有什么方法可以做到这一点吗?您可以编写一个函数,使用symfony的函数来检索值。扩展实现的示例如下所示:
<?php
use Symfony\Component\PropertyAccess\PropertyAccess;
class PropertyAccessorExtension extends \Twig_Extension
{
/** @var PropertyAccess */
protected $accessor;
public function __construct()
{
$this->accessor = PropertyAccess::createPropertyAccessor();
}
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('getAttribute', array($this, 'getAttribute'))
);
}
public function getAttribute($entity, $property) {
return $this->accessor->getValue($entity, $property);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*
*/
public function getName()
{
return 'property_accessor_extension';
}
}
快乐编码 你为什么要这样做?我想你是想这样做的?该链接摘录:你必须做
attribute(attribute(attribute(discussion,'child'),'prop1')
,因为{{attribute(entity,child.child.prop1')}==$entity['child.child.prop1']
@griotteau-Thx就是这样。谢谢,我本来打算做的:)
{% for entity in array %}
{{ getAttribute(entity, "child.child.prop1") }}
{% endfor %}