Foreach loops are needed everywhere. No matter if you build a menu, a simple list of subpages, a gallery, a table of contents, in short, whenever dealing with collections, arrays etc. – foreach loops are your best friends.
In this example, we build a very basic menu for all listed main pages in the content folder.
As you can see, this is just a matter of seven lines of code. As soon as you want to get some more control over each item in the loop, it can get quickly get more complex.
Whenever you get a set of pages in Kirby, like:
The result (
$items) is not just a plain, boring array. Kirby has its own array implementation, which comes with a few nice methods that make your life easier.
In many situations, we have to get the first or the last item, for example, to add a special class to these items (to style them or for other reasons). This is very easy with Kirby's methods:
With these methods we can create a nicer version of the menu above, with a class added to one of these items.
This can be modified to work for the first item instead…
You can search an element within a set of pages with the
find() or the
Both methods will only return a single page object, like the
We can use that search result to assign a class selector in our menu to a specific item:
Doesn't sound useful? Think about it again! You can use this to customize single items in any kind of menu, list, gallery, etc. without writing huge amounts of extra code. Since the
findBy method can search for all custom fields in your content file for each page, this can be very powerful. Just use your imagination :)
You can also fetch a particular item by its position in the collection, using the
In some situations it is useful to get the index number of an element in the collection, for example to add the number to a class name for a gallery or something like this. This can be achieved with the
offset() methods we can pick only a number of elements from our collection:
We can also exclude elements, for example to get all main pages for our menu, no matter if they are listed or unlisted, but not the error and home pages. This can be done with the
The same methods outlined above are not only available for pages, but also for collections of files, users, structure items or any other collection.
More methods in the Reference