Skip to content
This repository has been archived by the owner on Feb 11, 2021. It is now read-only.

Block collection

Bastian Allgeier edited this page Aug 6, 2019 · 2 revisions

The blocks field method returns a Blocks collection. This is a typical Kirby collection object (comparable to Pages, Files, Users etc.) with all available Block objects.

Render the entire collection

If you want to get the HTML for all blocks in the collection you can use the html method or convert the collection to a string

<?= $page->text()->blocks() ?>

… or …

<?= $page->text()->blocks()->html() ?>

Looping through blocks

<?php foreach ($page->text()->blocks() as $block): ?>
<!-- create some custom HTML for each block -->
<?php endforeach ?>

Useful collection methods

$blocks->count()

Returns the number of blocks

<?php if ($page->text()->blocks()->count()): ?>
<div class="blocks">
  <?= $page->text()->blocks() ?>
</div>
<?php endif ?>

$blocks->filterBy()

Filters the collection by the given arguments

<?= $page->text()->blocks()->filterBy('type', 'h1') ?>

$blocks->first()

Returns the first block

$blocks->html()

Renders all blocks

$blocks->last()

Returns the last block

$blocks->limit($limit)

Returns a limited number of blocks

$blocks->nth($index)

Returns the block at the given index

$blocks->offset($offset)

Returns the collection, starting at the given offset

$blocks->slice($offset, $count)

Returns a subset of all blocks

$blocks->toArray()

Converts all blocks to simple arrays