How to get specific element from block

Hello community I am in need of litle help from you.

My intention is to have a page having an overview of headings, something like a small table of content, than bellow it it’s a toBlocks field. something like this

++++
Table of content
- A list of all h1 or h2 elements from textblock()->toBlocks()
++++
Content

The template of that page looks like this:

<h1><?= $page->title() ?></h1>
<h2>Table of content</h2>

<ul>
    <li>...</li>
</ul>

<?= $page->textblock()->toBlocks() ?>

now, unfortunately I have no Idea how to pull all h1, h2 or h3 elements from textblock()

You can filter blocks by type:

$blocks = $page->textblocks()->toBlocks()->filterBy('type', 'heading');

Or if you use separate blocks for h1 etc.

$blocks = $page->textblocks()->toBlocks()->filterBy('type', 'in', ['h1', 'h2', 'h3']);
1 Like

As always, great reply by you @texnixe - I’made a big step forward for implementing my idea.

I did this, and it almost worked:

<ul>
  <?php foreach ($page->textblock()->toBlocks()->filterBy('type', 'sectionheading') as $heading) : ?>
    <li><a href="#<?= $heading->escape() ?>"><?= $heading ?></a></li>
  <?php endforeach ?>
</ul>

What i want is to implement anchor links to every list element. The anchor link should be same like $heading but stripped of its h1 or h2 tags. But using $heading->escape() isn’t working for me.

The problem with the above is that $heading is a block item, so you have to get the field value from the block. Don’t know what fields you have in your block…

This is how the sectionheading.php block looks like

<div class="card--section-block">
<?php /** @var \Kirby\Cms\Block $block */ ?>
<<?= $level = $block->level()->or('h2') ?>><?= $block->text() ?></<?= $level ?>>
</div>

Your section heading doesn’t have an id to link to with the anker, so you would have to add this first, $block->text()->slug().

Then in your anker link, use $heading->text()->slug().

1 Like