从字符串访问子实体属性 - Twig / Symfony

Nik*_*car 5 php symfony twig

如何访问twig. 例子 :

这是工作:

{% for entity in array %}
    {{ entity.child.child.prop1 }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

我不会将 s 字符串作为参数传递来获得相同的结果:

{% for entity in array %}
    {{ attribute(entity, "child.child.prop1") }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

但我得到错误:

对象“CustomBundle\Entity\Entity1”的方法“child.child.prop1”不存在...

有没有办法做到这一点?

xii*_*dea 3

您可以使用 symfony 的PropertyAccess 组件来检索值的函数编写自定义 twig 扩展。一个示例扩展实现可以是这样的:

<?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';
    }
}
Run Code Online (Sandbox Code Playgroud)

将此分机注册为服务后,您可以调用

{% for entity in array %}
    {{ getAttribute(entity, "child.child.prop1") }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

快乐编码!