3

I'm building out my first Craft site and learning a whole lot so far. Coming from ExpressionEngine, this really seems like what EE should have been.

Anyway, I'm trying to find a way divide up content from a table field into three even columns. For example, if I have content in 9 rows in a table, I would like to have 3 items per column. Is this possible with Twig? Here is the HTML. Thank you!

<div class="medium-3 medium-offset-2 small-centered medium-uncentered columns">
    <ul>
        <li>item</li>
        <li>item</li>
        <li>item</li>
    </ul>
</div>

<div class="medium-3 medium-offset-2 small-centered medium-uncentered columns">
    <ul>
        <li>item</li>
        <li>item</li>
        <li>item</li>
    </ul>
</div>

<div class="medium-3 medium-offset-2 small-centered medium-uncentered columns">
    <ul>
        <li>item</li>
        <li>item</li>
        <li>item</li>
    </ul>
</div>
6

It's actually quite simple! What you're looking for is Twig's batch filter... Ironically, the example given on that page is nearly identical to what you are requesting.

I've adapted the example to more closely match what you're looking for:

{% set myData = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}

{% for column in myData|batch(3, 'No item') %}
    <div class="medium-3 medium-offset-2 small-centered medium-uncentered columns">
        <ul>
            {% for item in column %}
                <li>{{ item }}</li>
            {% endfor %}
        </ul>
    </div>
{% endfor %}
  • Thanks Lindsey, I did see that, however this will create multiple columns with ONLY three list items in that column. What I actually need is ONLY three columns at the most that can divide up the amount of list items – ninjaroll May 28 '15 at 18:38
  • 1
    With a little addition to the solution of Lindsey you can achieve this. Instead of using a fixed value "3" for the batch you could calculate the size of each list before. {% set loopLength = myData|length % 3 %} {% for column in myData|batch(loopLength, 'No item') %} – Pascal Mollet Jun 19 '15 at 14:14
  • @PascalMollet This worked like a charm for me! But instead i divided the array by the number of columns I wanted, instead of using % – Jason Mayo Jan 18 '18 at 10: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.