1

I'm trying to build a feed of entries in a column grid. Something like that:

<div class="column">
 <a class="entry">First entry</a>
 <a class="entry">Fourth entry</a>
</div>

<div class="column">
 <a class="entry">Second entry</a>
 <a class="entry">Fifth entry</a>
</div>

<div class="column">
 <a class="entry">Third entry</a>
 <a class="entry">Sixth entry</a>
</div>

How do I achieve that? In my head .batch(3) only works horizontally for rows.

Edit: To make it more clearly, that's my goal and the reason for columns instead of rows:

Column Grid

2 Answers 2

1

There's no easy twig function available to do this, but the code from this answer should be able to help you.

{% set columns = 3 %}
{% for entry in entries %}
    {% if loop.first or loop.index0 is divisibleby(columns) %}
        <tr>
    {% endif %}

    <td>{{ entry.title }}</td>

    {% if loop.last and loop.index is not divisibleby(columns) %}
        {% for n in range(low=columns - (loop.index % columns), high=1, step=-1) %}
            <td>&nbsp;</td>
        {% endfor %}
    {% endif %}

    {% if loop.last or loop.index is divisibleby(columns) %}
        </tr>
    {% endif %}
{% endfor %}
1
  • That's a good start, but how can that work with different columns as <div>s?
    – Malte
    Commented Sep 10, 2017 at 20:09
1

You'll need to loop through all entries first and divide the entries into three arrays. Then using a combination of id and fixedOrder you can create three more entries calls to loop through each column and it's entries.

This would make a nice dynamic solution that doesn't need refactoring as more entries are added.

https://craftcms.com/docs/templating/craft.entries#fixedOrder https://craftcms.com/docs/templating/craft.entries#id

1
  • Sounds great! Can you give me a boost with a small example of the syntax? I don't know how exactly to accomplish this with twig.
    – Malte
    Commented Sep 11, 2017 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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