1

I'm trying to use Twig to display a simple list of Doctrine 2 entity objects. The objects are fetched with the untouched results from a DQL query. The PHP code is like this:

/*
 * I know the query in the Repository class works as I get the correct objects
 * from the method and can iterate through them with foreach in PHP, displaying
 * data from the object through getters, like ->getId()
 */
$received = $repo->getReceived($id);

/*
 * This appears to work, the variables are assigned correctly.
 */
echo $template->render(array("received" => $received, "first" => $received[0]));

The Twig template contains this:

{% for item in received %}
    <li>Item: {{ item.id }}, {{ first.id }}</li>
{% endfor %}

The strange thing is that twig iterates through the received array correctly, there are three objects in the array and there are three lines output but the id (or any other member) doesn't come out when accessed as item.id but the second output, first.id, comes out correctly.

What I should be seeing is this:

Item 1, 1
Item 2, 1
Item 3, 1

but instead I'm seeing:

Item , 1
Item , 1
Item , 1

I've tried different variations to get the output but nothing has worked so far, item.getId, item.getId().

Any ideas what I am missing here?

Edit dump output

{{ dump(received) }} returns the following:

array(3) {
  [0]=>
  object(Received)#219 (6) {
    ["id":"Received":private]=>
    int(1)
  ... snip ...
  }
  [1]=>
  object(Received)#208 (6) {
    ["id":"Received":private]=>
    int(2)
  ... snip ...
  }
  [2]=>
  object(Received)#210 (6) {
    ["id":"Received":private]=>
    int(3)
  ... snip ...

I've cut it down, these are three full blown Doctrine entity objects so they are in the array and look correct.

4

1 回答 1

0

I've finally found a way around this although I can't understand why I need to do it. I changed the array to contain a set of arrays instead of objects but that didn't work either.

I then created an alternative array for testing with the exact same structure and that array worked without any problems. Anyone have any idea what might cause one array to work while the other fails? Both are two dimensional arrays.

So what I ended up with was that I used the two dimensional array and changed the twig code to:

{% for item in received %}
    <li>Item: {{ attribute(item, 'id') }}</li>
{% endfor %}

For some reason attribute() is needed there although I did try that previously but then Twig complained that attribute() didn't exist.

Hopefully this will help some others.

于 2013-06-24T13:54:32.600 回答