Symfony Twig:使用可变属性获取对象属性

Med*_*ali 2 variables attributes object symfony twig

Symfony 3.0:

在我的项目中,我有许多包含超过 50 个字段的实体,因此对于显示每个实体的树枝,我决定通过一个简单的循环自动显示 50 个字段。

第一个问题:如何获取实体的所有字段名称,我通过创建自定义树枝过滤器解决了这个问题:

<?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';
    }
}

?>
Run Code Online (Sandbox Code Playgroud)

现在产生错误的第二个问题:如何在循环中访问对象属性:

        {% 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%} 
Run Code Online (Sandbox Code Playgroud)

错误 :

An exception has been thrown during the rendering of a template ("Notice: Array to string conversion").
500 Internal Server Error - Twig_Error_Runtime
Run Code Online (Sandbox Code Playgroud)

最后,错误是固定在过滤器的“getObjectKeys”方法上,

所以当它返回一个我手动创建的数组时,它可以工作:

return array("reference","libelle");
Run Code Online (Sandbox Code Playgroud)

但是,当我发送在循环中创建的数组时 => 错误。

我在树枝中转储了两个数组,它们是等价的,但第二个仍然产生错误。

Dar*_*Bee 6

您的一个属性很可能是返回一个数组而不是简单的string, integer, ...。这里的解决方案可能是将值存储在变量中并检查存储的值是否为数组。根据该检查对值执行某些操作,否则仅输出变量

{% 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%} 
Run Code Online (Sandbox Code Playgroud)