webGuy
webGuy

Reputation: 163

Access variable inside a loop and variable in Twig

I would like to do the following:

{% for i in 0..10 %}
    {% if content_{{ i }}_raw == 2 %} 
        ...
    {% endif %}
{% endfor %}

Is it possible to get {{ i }} inside the variable content_1_raw and replace the 1 with the value of i?

Upvotes: 3

Views: 785

Answers (1)

Matias Kinnunen
Matias Kinnunen

Reputation: 8550

Yes. The _context variable holds all variables in the current context. You can access its values with the bracket notation or using the attribute function:

{% for i in 0..10 %}
    {% if _context['content_' ~ i ~ '_raw'] == 2 %} 
        ...
    {% endif %}

    {# or #}

    {% if attribute(_context, 'content_' ~ i ~ '_raw') == 2 %} 
        ...
    {% endif %}
{% endfor %}

I have written more details about this here: Symfony2 - How to access dynamic variable names in twig

Also, instead of writing 'content_' ~ i ~ '_raw' (tilde, ~, is string concatenation operator), you can also use string interpolation:

"content_#{i}_raw"

Upvotes: 3

Related Questions