Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - How to call a object method using variable

Tags:

php

twig

symfony

I'm trying to fill a grid, but I don't know how call a object method using a variable. Variable "menus" is my entities, and "itens" is an array with what I wanna show in this grid.

    $itens = array(
            array('name' => 'id', 'label' => 'Id'),
            array('name' => 'parent', 'label' => 'Pai'),
            array('name' => 'name', 'label' => 'Nome'),
            array('name' => 'route', 'label' => 'Rota'),
            array('name' => 'position', 'label' => 'Posição'),
    );

Here's my code:

{% for menu in menus %}
    <tr>
        {% for item in itens %}
            <td>{{ attribute(menu, item['name']) }}</td>
        {% endfor %}
    </tr>
{% endfor %}

I tried too with menu.item['name'], but without success... Any idea?

like image 471
Eduardo K Avatar asked Oct 04 '13 19:10

Eduardo K


People also ask

How do you use variables in twig?

In Twig templates variables can be accessed using double curly braces notation {{ variableName }} .

Can you use twig in Javascript?

Twig and JS code is more tightly knit. You can easily transfer Twig variables into JS. Your code is more portable - you can easily reuse component by just copying a single file to other project.


1 Answers

I got it!!! I did this:

    {% for menu in menus %}
        <tr>
            {% for item in itens %}
                {% set method %}{{ item['name'] }}{% endset %}
               <td>{{ attribute(menu, method) }}</td>
            {% endfor %}
        </tr>
    {% endfor %}
like image 92
Eduardo K Avatar answered Oct 12 '22 23:10

Eduardo K