0

How could I declare variables in a loop using Twig from a "users" array of objects "user" retrieved from the controller?

user1 = "user1"

user2 = "user2"

...

userN = "userN" (with N length of the array)

{% for user in users %}

  {% set user1 = "user1" %} 
  {% set user2 = "user2" %}
   ...

{% endfor %}
4

1 回答 1

2

Twig gives you different loop variables, that you can use in the loops.

http://twig.sensiolabs.org/doc/tags/for.html#the-loop-variable

As for implementation of dynamic variable names - Twig does not support this, AFAIK.

In your case, I guess you need to refactor your application logic to work inside the loop:

{% for user in users %}
   {% set currentUser = "user" ~ loop.index %}
   ...do your includes, code etc. related to userN, assuming that userN == user ...
{% endfor %}
于 2012-07-25T07:57:35.197 回答