【问题标题】:Symfony Twig : get Object property with a variable propertySymfony Twig:使用变量属性获取对象属性
【发布时间】:2017-10-31 22:15:16
【问题描述】:

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

?>

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

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

错误:

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

最后在过滤器的“getObjectKeys”方法上修复了错误,

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

return array("reference","libelle");

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

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

【问题讨论】:

  • 您的一个属性是返回一个数组而不是一个字符串值
  • @DarkBee :好推理我的朋友,我有一些对象字段。那么你在我的情况下建议什么?我应该为每个实体创建一个方法,该方法返回一个数组,其中包含与该值关联的实体属性名称(手动)。

标签: symfony variables object attributes twig


【解决方案1】:

您的某个属性很可能返回一个数组,而不是简单的stringinteger...。这里的解决方案可能是将值存储在变量中并检查存储的值是否为数组。根据该检查对值做一些事情,或者只是输出变量

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 2013-01-07
    • 2022-08-23
    • 1970-01-01
    • 2018-04-15
    相关资源
    最近更新 更多