Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP & Twig : Trouble accessing variables in template

In my controller I am setting the following variables and passing them to the Twig template:

$data = $model::all(); // returns object [phpactiverecord]
$fields = getFields(); // returns associative array

In my template, I am attempting the access them like this:

{% block rows %}
  {% for row in data %}
            <tr>
    {% for field in fields %}
              <td>{{ row[field.name] }}</td>
    {% endfor %}
            </tr>
  {% endfor %}
{% endblock %}

In this scenario, $fields is defined as:

Array
(
    [0] => Array
        (
            [name] => id
            [display] => Id
        )

    [1] => Array
        (
            [name] => name
            [display] => Name
        )

)

and $data is an array of phpactiverecord objects.


As written above, nothing is output for row[field.name].

Here are the results I see if I change row[field.name]:

row.name        -> outputs Value I would expect from row[field.name]
field.name      -> outputs "name"
row['name']     -> outputs nothing
row[field.name] -> outputs nothing

According to the Twig site: You can use a dot (.) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array), or the so-called “subscript” syntax ([]):

Any ideas on getting this to work?

like image 683
sonicradish Avatar asked Oct 09 '22 00:10

sonicradish


1 Answers

If you're using version 1.2 or later, try the attribute function

{{ attribute(row, field.name) }}

It's even mentioned on the page you linked to...

If you want to get a dynamic attribute on a variable, use the attribute function instead.

like image 155
Phil Avatar answered Oct 12 '22 21:10

Phil