0

I am using twig.js for templating. I have html div which displays 3 items from the items list.

<div class="item-container">
    {% set i = 0 %}
    {% for i in 0..items | length %}
    <ul>
        <li> {{ items[i].name }}     </li>
        <li> {{ items[i + 1].name }} </li>
        <li> {{ items[i + 2].name }} </li>
    <ul>
    {% set i = i + 3 %}
    {% endfor %} 
</div>

First iteration loop works fine, but $i will not be incremented using {% set i = i + 3 %}.
Can anyone tell me how to do this ?

1
  • I see there are valid solutions, but I'd still like to add the batch filter as an alternative. Commented May 7, 2014 at 13:52

1 Answer 1

4

Use range function, it has step argument:

<div class="item-container">
{% for i in range(0, items|length-1, 3) %}
    <ul>
        <li>{{ items[i] }}</li>
        <li>{{ items[i+1]|default }}</li>
        <li>{{ items[i+2]|default }}</li>
    </ul>
{% endfor %}
</div>

Instead of default filter you may use {% if items[i+1] is defined %}.

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

2 Comments

This works fine, if items length is more than step value. In case the item length is less than step value, twig will throw error.
@geekgugi Just wrap the loop with if clause checking items|length < 3 or add this condition before defining the range.

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.