Generating lists for items in a collection in multiples of 5

Hello there! I attempted searching for a solution to this, but am having trouble adequately describing what I’m trying to accomplish, so please bear with me if this has already been answered. I have a very shallow understanding of php, and I’ve been able to use the documentation for most everything I need on my site, but this one has stumped me.

What I’m trying to do is generate a nav menu for subpages, but do so in a way that puts each item into “slots,” where the slots are in groups of 5.

To be more specific, I’m I have a unordered list and I want to generate a list item for each item in the collection of subpages. The tricky part is that if the number of items in the collection is not a multiple of 5, then I want to generate empty list items to fill out the last set of 5.

This is the basic sub menu code I’m accustomed to using

<?php

$items = false;

// get the open item on the first level
if($root = $pages->find('pagename')) {

  // get visible children for the root item
  $items = $root->children()->visible();
}

// only show the menu if items are available
if($items and $items->count()):

?>

    <ul> 
        <?php foreach($items as $item): ?>
            <li>
                <div>content</div>
            </li>
        <?php endforeach ?>
    </ul> 

<?php endif ?>

I’ve included a couple of example scenarios to demonstrate end result I’m wanting to achieve.

Example Scenario 1:
4 items in the collection.
5 list items generated, with the remainder of 1 represented by a single empty list item.

<ul>
    <li><div>content</div></li>
    <li><div>content</div></li>
    <li><div>content</div></li>
    <li><div>content</div></li>
    <li></li>
</ul>

Example Scenario 2:
7 items in the collection.
10 list items generated (next multiple of 5), with a remainder of 3.

<ul>
    <li><div>content</div></li>
    <li><div>content</div></li>
    <li><div>content</div></li>
    <li><div>content</div></li>
    <li><div>content</div></li>
    <li><div>content</div></li>
    <li><div>content</div></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

Quick and dirty:

<ul> 
    <?php foreach($items as $item): ?>
        <li>
            <div>content</div>
        </li>
    <?php endforeach ?>
    <?php for($x = 5 - ($items->count()%5); x > 0; $x--) { ?>
        <li></li>
    <?php } ?>
</ul>

Basically something like 5 - ($items->count()%5) should give you the number of list items that are missing for a full block of 5.

1 Like