Accessing a child from a string - Twig / Symfony

How to access the value of a property of a child in twig. Example:

This is wokring:

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

I do not want to pass the s-string as a parameter in order to get the same thing:

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

But I get the error:

The method "child.child.prop1" for the object "CustomBundle \ Entity \ Entity1" does not exist ...

Is there any way to do this?

+4
source share
1 answer

You can write a custom twig extension with a function that uses PropertyAccess for symfony to get the value. An example implementation of an extension may be as follows:

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

!

+1

Source: https://habr.com/ru/post/1538580/


All Articles