Как получить доступ к значению свойства дочернего объекта в twig
. Пример:
Это wokring:
{% for entity in array %}
{{ entity.child.child.prop1 }}
{% endfor %}
Я не хочу передавать s-строку в качестве параметра, чтобы получить одно и то же:
{% for entity in array %}
{{ attribute(entity, "child.child.prop1") }}
{% endfor %}
Но я получаю ошибку:
Метод "child.child.prop1" для объекта "CustomBundle\Entity\Entity1" не существует...
Есть ли способ сделать это?
Вы можете написать пользовательское расширение твига с функцией, которая использует PropertyAccess для symfony для получения значения. Пример реализации расширения может быть следующим:
<?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 %}
Счастливое кодирование!