如何在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 %}
快乐的编码!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。