[英]Symfony Twig : get Object property with a variable property
Symfony 3.0 : Symfony 3.0:
In my project, I have many entities which contains more than 50 fields, so that for the twig which show every entity, i decided to automate the display of the 50 fields by a simple loop. 在我的项目中,我有许多包含50多个字段的实体,因此对于显示每个实体的树枝,我决定通过一个简单的循环自动显示50个字段。
First problem : how to get entity's all fields names, i resolved this by creating a custom twig filter : 第一个问题:如何获取实体的所有字段名称,我通过创建自定义树枝过滤器解决了此问题:
<?php
// src/HomeBundle/Twig/HomeExtension.php
namespace HomeBundle\Twig;
class HomeExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('object_keys', array($this, 'getObjectKeys')),
);
}
public function getObjectKeys($object)
{
//Instantiate the reflection object
$reflector = new \ReflectionClass( get_class($object) );
//Now get all the properties from class A in to $properties array
$properties = $reflector->getProperties();
$result=array();
foreach ($properties as $property)
$result[] = $property->getName();
return $result;
}
public function getName()
{
return 'app_extension';
}
}
?>
Second problem which generate the error right now : how to access to object properties within a loop: 现在产生错误的第二个问题:如何在循环中访问对象属性:
{% for property in article|object_keys%}
<tr>
<th>
{{property|capitalize}} {# that's work clean #}
</th>
<td>
{{ attribute(article,property) }} {# that's generate the error #}
</td>
</tr>
{% endfor%}
The error : 错误 :
An exception has been thrown during the rendering of a template ("Notice: Array to string conversion").
500 Internal Server Error - Twig_Error_Runtime
Finally, the error is fixed on the "getObjectKeys" method of the filter, 最后,错误已通过过滤器的“ getObjectKeys”方法修复,
so when it return an array that I create manually it works : 因此,当它返回我手动创建的数组时,它可以工作:
return array("reference","libelle");
But, when I send an array created within a loop => Error. 但是,当我发送在循环中创建的数组=>错误时。
I dumped the two arrays in the twig, they were equivalents, but the second still generating an error. 我将这两个数组转储到树枝中,它们是等效的,但第二个数组仍然产生错误。
Most likely one of your properties is returning an array rather than a simple string
, integer
, ...
. 您的属性中最有可能的一个属性是返回一个数组,而不是简单的
string
, integer
...
。 A solution here could be to store the value in a variable and check whether the stored value is an array. 一种解决方案是将值存储在变量中,并检查存储的值是否为数组。 Depending on that check do something with the value or otherwise just output the variable
根据该检查,对值进行处理,否则仅输出变量
{% for property in article|object_keys%}
<tr>
<th>
{{property|capitalize}}
</th>
<td>
{% set value = attribute(article,property) %}
{% if value is iterable %}{# test if value is an array #}
{{ value | join(', ') }}
{% else %}
{{ value }}
{% endif %}
</td>
</tr>
{% endfor%}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.