문제

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?

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top