Count and running index of all blocks in a layout field of subpages

Hi! I’m a bit stuck with this so I’m hoping someone might be able to help me out.

I’m making a table of contents type of thing for a series of projects (subpages). I would like the numbers next to the project title to count all the blocks in one of the layout fields (called layout in this case) of that project (subpage) and then show the number span for that subpage (like with a page count in a book). And then the next project should start from the next number and do the same for that one, and so on.

I’m guessing I have to do some kind of loop and I see that it’s possible to get the count of blocks and layouts, but I just can’t quite get how to put it all together. When I tried the layouts()->count() I just got the number 2 which I don’t see how could be correct so I’m not sure what’s happening. Here’s an image of how I would ideally like it to work:

Hi, welcome to the forum.

With

dump($page->layout()->toLayouts()->count());

you get the number of layouts in the page.

But you can also count all blocks in the layouts field like this:

dump($page->layout()->toBlocks()->count());

(layout() is the field name here)

Thank you so much Sonja! :slight_smile: That works perfectly to count how many there are in each project. Now, for the next part I guess there is a pretty simple way to do this as well, but I’m kind of grasping at straws here. I guess it would have to remember in each iteration the previous value and change the numbers on each side of the hyphen correspondingly?

Yes, you can use a counter that keeps track of the actual value within the loop. Then on each loop, you add the current block count to the counter variable.

1 Like

Yay, this worked perfectly! Thanks again! :slight_smile: