我试图在不知道对象结构的情况下显示User对象中的所有用户(因此我也可以使用同一个表来显示其他对象集合)。
这就是“静态”看起来的样子:
<table> <tr> <td>id</td> <td>username</td> </tr> {% for item in entities %} <tr> <td>{{ item.id }}</td> <td>{{ item.username }}</td> </tr> {% endfor %} </table>我想要做的是如下(这只是为了显示我正在尝试做的事情,但它甚至不接近工作):
<table> <tr> {% for property_title in entities.item[0] %} <td>{{ property_title }}</td> {% endfor %} </tr> {% for item in entities %} <tr> {% for property in item %} <td>{{ property.value }}</td> {% endfor %} </tr> {% endfor %} </table>结果应如下所示:
<table> <tr> <td>id</td> <td>username</td> </tr> <tr> <td>1</td> <td>Mike123</td> </tr> <tr> <td>2</td> <td>jesica2</td> </tr> </table>PD:这是我的第一篇文章,如果我错过了什么,请道歉。
I'm trying to display all the users in my User object without knowing the structure of the object (so I can use the same table to display other collection of objects as well).
This is what it would look 'statically':
<table> <tr> <td>id</td> <td>username</td> </tr> {% for item in entities %} <tr> <td>{{ item.id }}</td> <td>{{ item.username }}</td> </tr> {% endfor %} </table>What i would want to do is something as follows (this is just to display what I'm trying to do, but its not even close to working):
<table> <tr> {% for property_title in entities.item[0] %} <td>{{ property_title }}</td> {% endfor %} </tr> {% for item in entities %} <tr> {% for property in item %} <td>{{ property.value }}</td> {% endfor %} </tr> {% endfor %} </table>Result should be something as follows:
<table> <tr> <td>id</td> <td>username</td> </tr> <tr> <td>1</td> <td>Mike123</td> </tr> <tr> <td>2</td> <td>jesica2</td> </tr> </table>PD: this is my first post, so apologies if I missed something.
最满意答案
制作一个枝条扩展名,返回您想要的字段列表,这样您就可以使用php来获取字段。 之后使用twig的属性函数
{{attribute(object,fields)}}调用对象上的getter
文档:
http://symfony.com/doc/current/cookbook/templating/twig_extension.html http://twig.sensiolabs.org/doc/functions/attribute.html
例:
{% set temp = entities|first %} {% set fields = getObjectFields(temp) %} <tr> {% for property_title in fields %} <td>{{ property_title }}</td> {% endfor %} </tr> {% for item in entities %} <tr> {% for field in fields %} <td>{{ attribute(item, field) }}</td> {% endfor %} </tr> {% endfor %}Make a twig extension that returns a list of the fields you want, that way you can use php to get the fields. After that use twig's attribute function
{{ attribute(object, fields) }} to call the getters on the object
docs:
http://symfony.com/doc/current/cookbook/templating/twig_extension.html http://twig.sensiolabs.org/doc/functions/attribute.html
example:
{% set temp = entities|first %} {% set fields = getObjectFields(temp) %} <tr> {% for property_title in fields %} <td>{{ property_title }}</td> {% endfor %} </tr> {% for item in entities %} <tr> {% for field in fields %} <td>{{ attribute(item, field) }}</td> {% endfor %} </tr> {% endfor %}更多推荐
发布评论