Displaying table in twig dynamically
html, symfony, twig
Solution
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 %}
Problem
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.