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

如何在twig中访问子实体属性值.示例:

这就是:

{% for entity in array %}
    {{ entity.child.child.prop1 }}
{% endfor %}

我不会将s字符串作为参数传递给同样的东西:

{% for entity in array %}
    {{ attribute(entity, "child.child.prop1") }}
{% endfor %}

但我得到错误:

Method “child.child.prop1” for object “CustomBundle\Entity\Entity1”
does not exist…

有没有办法做到这一点?

最佳答案 您可以使用函数使用symfony的
PropertyAccess component来编写
custom twig extension以检索该值.示例扩展实现可以是:

<?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';
    }
}

registering this extension as service之后,您可以打电话

{% for entity in array %}
    {{ getAttribute(entity, "child.child.prop1") }}
{% endfor %}

快乐的编码!

点赞