Reputation: 37
I am very new in Symfony and I have a problem in my twig. I just don't know how to do it :(
{% set trans_number = '' %}
{% for tran in trans %}
{% set trans_number = tran.transNumber %}
{{dump(trans_number)}}
// this is what I get when dumping inside the loop: string(10) "1073110793" string(10) "1073145793" string(12) "646721454679"
{% endfor %}
But when I tried to dump it outside the loop:
{% set trans_number = '' %}
{% for tran in trans %}
{% set trans_number = tran.transNumber %}
{% endfor %}
{{dump(trans_number)}}
// I get only the last value string(12) "646721454679"
Now my question is, how can I access all the values assigned to the trans_number outside the loop? Thanks in advance.
Upvotes: 0
Views: 907
Reputation: 3523
For people looking for the answer to the question in the title of the question:
You could use the last Filter
Example:
{{ dump( (trans|last) ) }}
Source: http://twig.sensiolabs.org/doc/filters/last.html
Upvotes: 0
Reputation: 16512
You're correct with the variable scope and handling the scope access by declaring trans_number
before the loop, however you're misinterpreting how set
works with Twig, or just how variables work.
When you use set trans_number = tran.transNumber
, you're just assigning a new value to the trans_number
variable each time. When you move the dump
outside of the loop, you're no longer dumping the new value of trans_number
through each iteration.
If you wish to build a list of values into trans_number
, then you need to initialize trans_number
as a list and append to it through each iteration of the for
loop:
{% set trans_number = [] %}
{% for tran in trans %}
{% set trans_number = trans_number|merge([tran.transNumber]) %}
{% endfor %}
{{dump(trans_number)}}
Upvotes: 2