I’m trying to add the index number of this particular block even when there are different blocks types in between
(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
<?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.
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; ?>
<?php endforeach ?>
Would only make sense like this with single images, for galleries you would have to extend the example.