Incremental id's for structure loop

Hi all - Iā€™m looping through structure panel field to create a boostrap accordion; trouble is I need a unique id for each accordion section. What is the best way to incrementally create an id based on the item number in the loop?

<?php 
$items = $data->accordionContent()->toStructure();
foreach ($items as $item): ?>
      <div class="card-header" id="headingOne">
        <h2 class="mb-0">
          <button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
            <?= $item->sectionTitle() ?>
          </button>
        </h2>
      </div>
      <div id="collapseOne" class="collapse show" aria-labelledby="headingOne" data-parent="#accordion">
        <div class="card-body">
        <?= $item->sectionText()->html() ?>
        </div>
      </div>
<?php endforeach ?>

</div>
</div>

Thanks!

You can use $item->indexOf($items) to get the position of the item in the collection. The alternative would be to add ids to structure items, e.g. via the AutoID plugin.

1 Like

$item is a structureobject and should have an id() method.

2 Likes

Wow thanks, had no idea. Nice and simple :metal:t3: