3

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?

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

Comments

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.