Lukas Hillebrand
Lukas Hillebrand

Reputation: 416

for loop in TWIG with string concatenation?

How can I output this HTML block with a nested TWIG counter variable {{ i }} like: eco-item-2.jpg, eco-item-3.jpg and eco.benefits.item.header.2, eco.benefits.item.header.3 and so on…?

{% for i in 0..3 %}
    <section class="eco-benefits">
        <img src="{{ asset ('img/eco-item-1.jpg') }}" class="th">
        <dl>
            <dt>
                {% trans from 'eco' %}
                    eco.benefits.item.header.1
                {% endtrans %}
            </dt>
            <dd>
                {% trans from 'eco' %}
                    eco.benefits.item.text.1
                {% endtrans %}
            </dd>
        </dl>
    </section>
{% endfor %}

Upvotes: 0

Views: 3479

Answers (1)

xabbuh
xabbuh

Reputation: 5881

You can concatenate strings using the ~ operator:

{% for i in 0..3 %}
    <section class="eco-benefits">
        <img src="{{ asset ('img/eco-item-' ~ (i + 1) ~ '.jpg') }}" class="th">
        <dl>
            <dt>{{ ('eco.benefits.item.header.' ~ (i + 1))|trans(domain = 'eco') }}</dt>
            <dd>{{ ('eco.benefits.item.text.' ~ (i + 1))|trans(domain = 'eco') }}</dd>
        </dl>
    </section>
{% endfor %}

Upvotes: 4

Related Questions