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 %}

快乐的编码!

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...