Count the index of select block type

Iā€™m trying to add the index number of this particular block even when there are different blocks types in between

eg:
(01) hero block
other block type
(02) hero block

Iā€™m trying the select only the ā€˜herosectionā€™ block but my code below doesnā€™t work

site/snippets/blocks/herosection.php

<?php $hero = $block->type("herosection"); ?>
<?php if($hero->indexOf() < 9): ?>0<?php endif ?>
<?= $hero->indexOf() + 1 ?>

You cannot filter a single block type but only a collection of blocks, and there is no reason to when you are in your herosection block snippet anyway, since that only refers to this block type.

I actually think it would make more sense if you added your numbers via CSS counters : https://developer.mozilla.org/en-US/docs/Web/CSS/counters()

Iā€™d actually want to do something similar. In my case itā€™s counting the images on an article page and output the count of the figure to the figcaption, so automatically having ā€œFigure 1: abcā€, ā€œFigure 2: defā€ etc.

The CSS counters idea works fine, however is more difficult with internationalization (might somehow work with CSS vars, havenā€™t tried).

Is there any other way to attach the counter, or more general, additional data to that particular object? Afaik, I cannot change field data.

Thx!

One way to achieve that would be to loop through the blocks, then in the loop use an if statement that checks if the block type is an image, if thatā€™s the case, you increase a counter and instead of echoing the block, you call the block snippet and inject the counter variable (Blocks | Kirby):

<?php $counter = 0; ?>

<?php foreach ($page->myBlocksField()->toBlocks() as $block): ?>
  <?php if ( $block->type() === 'image' ) : $counter++; ?>
    <?php snippet('blocks/' . $block->type(), [
    'block' => $block,
    'counter' => $counter
  ]) ?>
  <?php else: ?>
    <?= $block ?>
  <?php endif; ?>
</div>
<?php endforeach ?>

Would only make sense like this with single images, for galleries you would have to extend the example.

1 Like