简体   繁体   English

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

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

How can I access child entity property value in twig . 如何在twig访问子实体属性值。 Example : 示例:

This is wokring : 这就是:

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

I wont to pass s string as param to get the same thing : 我不会将s字符串作为参数传递给同样的东西:

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

But I get error : 但我得到错误:

Method "child.child.prop1" for object "CustomBundle\\Entity\\Entity1" does not exist... 对象“CustomBundle \\ Entity \\ Entity1”的方法“child.child.prop1”不存在...

Is there any way to do that? 有没有办法做到这一点?

You can write a custom twig extension with a function that uses the PropertyAccess component of symfony to retrieve the value. 您可以使用函数编写自定义twig扩展 ,该函数使用symfony的PropertyAccess组件来检索值。 An example extension implementation can be Like: 示例扩展实现可以是:

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

After registering this extension as service , you can then call 将此扩展名注册为服务后 ,您可以调用

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

Happy coding! 快乐的编码!

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

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