How to show a list of blocks of certain type?

I want to do table of contents for each blog post. So it should be a list of all headings with H1 tags.

I haven’t used it myself but this field method from source code may help you get started:

You can simply filter all blocks by type

Nice thank you. Also question: I did block id for headings, but the problem is when I print only headings in table of contents as links to headings in blog post content, they also get this id’s and thus link to themselves, so what would be the solution to have id’s only in blog post content?

Maybe possible to create different snippets? One standard, and another one only for table of contents.

In any case you need to loop through the individual blocks rather than output them with toBlocks()

Thank you. Don’t know if I get your idea right, but actually works well with toBlocks(). I created custom snippet and loaded with:

  <?php foreach ($page->body()->toBlocks()->filterBy('type','heading') as $blo): ?>
  <div id="" class="block  block-type-<?= $blo->type() ?>">
    <a  href="#<?= $blo->id() ?>">
    <?php snippet('blocks/' . 'headingcontent', [
    'block' => $blo
  ]) ?>
  <?php endforeach ?>

All done, thanks a lot.

1 Like