I refer to the template written in the previous post:
<?php foreach ($column->blocks() as $index=>$block):
snippet('blocks/' . $block->type(), ['block' => $block, 'index' => $index]);
endforeach; ?>
then output this index value in block snippet
<?= $index ?>
But what I get is always 0,
What went wrong?
taoguangc:
$column->blocks()
$column->blocks() returns a blocks collection, so trying to access it as an array with key/value pairs won’t work.
What you can do instead, is use indexOf()
, i.e. $block->indexOf($column->blocks())
.
Thanks for viewing my question, sorry, I still don’t understand where to modify.
I want to display index number in sub block.
The following code snippet is quoted from the layout.
<?php foreach ($page->layout()->toLayouts() as $layout): ?>
<section class="6-column-grid" id="<?= $layout->id() ?>">
<?php foreach ($layout->columns() as $column): ?>
<div class="column" style="--span:<?= $column->span(6) ?>">
<div class="blocks">
<?php foreach ($column->blocks() as $block): ?>
<div class="block block-type-<?= $block->type() ?>">
<?php snippet('blocks/' . $block->type(), ['block' => $block, 'layout' => $layout]) ?>
</div>
<?php endforeach ?>
</div>
</div>
<?php endforeach ?>
</section>
<?php endforeach ?>
I want to get card number value in snippets/blocks/card.php
<div>
<h2>card number: <?= $index ?></h2>
<h3><?= $block->heading() ?></h3>
</div>
<?php foreach ($column->blocks() as $block):
snippet('blocks/' . $block->type(), ['block' => $block, 'index' => $block->indexOf($column->blocks())]);
endforeach; ?>
Yes, I used this code, but I still get “0” all the time.
Well, with this logic, you will get the index of the block inside the column. If a column only has a single block, the index will be 0. If you want to get the index of a given block with regard to all blocks in the field, then you have to change the reference of the index.
Great! I got it, $index should be defined from the parent.
<?php foreach ($page->layout()->toLayouts() as $layout): ?>
<section class="6-column-grid" id="<?= $layout->id() ?>">
<?php foreach ($layout->columns() as $column):
$index = $layout->columns()->indexOf($column); // defined $index here
?>
<div class="column" style="--span:<?= $column->span(6) ?>">
<div class="blocks">
<?php foreach ($column->blocks() as $block): ?>
<div class="block block-type-<?= $block->type() ?>">
<?php snippet('blocks/' . $block->type(), ['block' => $block, 'index' => $index]) ?>
</div>
<?php endforeach ?>
</div>
</div>
<?php endforeach ?>
</section>
<?php endforeach ?>