1

I have an unusual issue with a for loop divisible by. The code works fine initially as it loops through the entries and closes a the list element on the 4th loop. However when it gets to the end of the entries and there are less than 4 left it strangely adds them into the source but does not display them visually on the page or in chromes inspector?? Has anyone come across this before? Nothing is hiding the last entries and if I change divisible by to different values it does the same only show entries that are divisible by and loses the remainder.

The code is as follows:

{% if loop.first %}
  <li>
{% endif %}

..... code pulling out entry details into divs

{% if loop.index is divisible by(4) and not loop.last %}
  </li><li>
{% endif %}
{% if loop.last %}
  </li>
{% endif %}
2

You have some other bug somewhere else. Check the code pulling out entry details to be sure that it doesn't modify loop or the list you are looping on, or the current item.

This code works:

{% for item in (1..10) %}
  {% if loop.first %} [ {% endif %}
  {{ item }}
  {% if loop.index is divisible by(4) and not loop.last %}
    ] [
  {% endif %}
  {% if loop.last %} ] {% endif %}
{% endfor %}

And outputs this:

[ 1 2 3 4 ] [ 5 6 7 8 ] [ 9 10 ]

You can simplify it a bit:

{% for item in (1..10) %}
  {% if loop.first %} [ {% endif %}
  {{ item }}
  {% if loop.index is divisible by(4) or loop.last %}
    ] [
  {% endif %}
{% endfor %}

You also can use the batch filter, which I think makes things slightly clearer:

{% for b in (1..10) | batch(4) %}
  [
    {% for item in b %}
      {{ item }}
    {% endfor %}
  ]
{% endfor %}
1
  • Indeed it was something else. A rogue line of js removing the last list item. Cheers. – Lettie Oct 11 '17 at 15:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.