0

I want to reuse my twig variable for the loop outside the loop, but I can't! I've tried like this

{% set b = '' %}
{% set c = '' %}

{% for i,foo in cout %}
    {% set b = cout[i] %} 
    {{ b }} 
{% endfor %} 

{% for j,bar in efforts %} 
    {% set c = efforts[j] %}
    {{ c }} 
{% endfor %}

{{ b }} {{ c }}

But here it's return me the last value of b and c, so I want all value of c and b outside the loop, thanks!

1 Answer 1

0

Yes, you're overwriting variable b & c in every loop, that's why you see only the last one.

You have to use merge function here.

{% set b = [] %}    

{% for i,foo in cout %}
    {% set b = b|merge([cout[i]]) %}  
{% endfor %} 

As suggested by DarkBee, to output content of b array as a string you can use join function, iterate through array, or access values by keys or any other function provided by Twig.

Sign up to request clarification or add additional context in comments.

5 Comments

ok thanks, but merge function return me an error : The merge filter only works with arrays or "Traversable", got "string" as first argument. whenever I change {% set b = [] %} it's return error An exception has been thrown during the rendering of a template ("Notice: Array to string conversion").
Change {{ b }} to something like {{ b | join(',') }}
I've already do that, but I wan't to use array but not string :( I don't understand when I do {{ dump(b) }} it's return the array in console but {{ b }} return error
{% set b = b ~' '~ count[i] %}?
@KahanAm, My bad. I forgot to edit first line of your code. Please see updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.