6

How can I access child entity property value in 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 :

{% 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...

Is there any way to do that?

3
  • Why do you even want to do that ? Commented Apr 29, 2014 at 12:38
  • 5
    I think you want github.com/fabpot/Twig/issues/1296 ? Commented Apr 29, 2014 at 12:39
  • 1
    Excerpt of that link: you must do attribute(attribute(discussion, 'child'), 'prop1'), because {{ attribute(entity, "child.child.prop1") }} === $entity['child.child.prop1'] Commented Apr 29, 2014 at 13:02

1 Answer 1

3

You can write a custom twig extension with a function that uses the PropertyAccess component of symfony to retrieve the value. 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!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I was planning to do something like that :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.