How to get the index of the wp-each directive in Interactivity API Wordpress?

1 week ago 12
ARTICLE AD BOX

I am learning the interactivity API, and when I tried the wp-each directive, I noticed that there is no way to get the index of the array. e.g., if this is my array

$config = [ 'fruits' => [ [ 'id' => time() * 1000, 'data' => [ 'apple' => 10, 'orange' => 10, 'banana' => 10, ], ], ], ];

and this is my HTML

render.php

<ul data-wp-interactive="myNameSpace" class="gap-2 grid" <?php echo wp_interactivity_data_wp_context( $config ) ?> > <template data-wp-each="context.fruits" data-wp-key="context.item.id"> <li class="p-2 border border-slate-100 rounded-md" data-wp-bind--id="context.item.id"> <span data-wp-text="context.index"></span> </li> </template> </ul>

I checked the documentation, and it does not include anything related to the index.

I’m trying to access the index of each item inside an array while using the wp-each directive from the WordPress Interactivity API.

I know that using regular PHP like:

foreach ( $config['fruits'] as $index => $value ) { // ... }

would give me the index, and that works.

But since I’m learning and building with the Interactivity API, I’d like to know how to get the index directly inside wp-each, similar to how Vue provides (item, index) in v-for.

So my question is: Is there a way to access the array index inside wp-each? Or is wp-each currently limited to just iterating over values without exposing the index?

Read Entire Article