繁体   English   中英

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

[英]Access child entity property from string - Twig / Symfony

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

这就是:

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

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

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

但我得到错误:

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

有没有办法做到这一点?

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

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

将此扩展名注册为服务后 ,您可以调用

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

快乐的编码!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM