Display table in a branch dynamically

I am trying to display all users in a User object without knowing the structure of the object (so I can use the same table to display a different collection of objects).

This is what it will 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 like to do is something like this (this is just to show what I'm trying to do, but it is not even close to work):

<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>

The result should be 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 I apologize if I missed something.

+3
source share
2 answers

Make a branch extension that returns a list of the fields you want, so you can use php to get the fields. After that, use the twig attribute function

{{attribute (object, fields)}},

:

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 %}
+2

Derick F , , . , "fields" .

{% set temp = entities|first %}

<tr>
{% for property_title in temp|keys %} 
    <td>{{ property_title }}</td>
{% endfor %}
</tr>
{% for item in entities %}
    <tr>
        {% for field in temp|keys %}
            <td>{{ attribute(item, field) }}</td>
        {% endfor %}
    </tr>
{% endfor %}

, . .

datetime , , :

, date Twig

0

All Articles