You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: packages/interactivity/docs/2-api-reference.md
+72Lines changed: 72 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -552,6 +552,78 @@ But it can also be used on other elements:
552
552
553
553
When the list is re-rendered, the Interactivity API will match elements by their keys to determine if an item was added/removed/reordered. Elements without keys might be recreated unnecessarily.
554
554
555
+
556
+
#### `wp-each`
557
+
558
+
The `wp-each` directive is intended to render a list of elements. The directive can be used in `<template>` tags, being the value a path to an array stored in the global state or the context. The content inside the `<template>` tag is the template used to render each of the items.
559
+
560
+
Each item is included in the context under the `item` name by default, so directives inside the template can access the current item.
The prop that holds the item in the context can be changed by passing a suffix to the directive name. In the following example, we change the default prop `item` to `greeting`.
By default, it uses each element as the key for the rendered nodes, but you can also specify a path to retrieve the key if necessary, e.g., when the list contains objects.
593
+
594
+
For that, you must use `data-wp-each-key` in the `<template>` tag and not `data-wp-key` inside the template content. This is because `data-wp-each` creates
595
+
a context provider wrapper around each rendered item, and those wrappers are the ones that need the `key` property.
596
+
597
+
```html
598
+
<uldata-wp-context='{
599
+
"list": [
600
+
{ "id": "en", "value": "hello" },
601
+
{ "id": "es", "value": "hola" },
602
+
{ "id": "pt", "value": "olá" }
603
+
]
604
+
}'>
605
+
<template
606
+
data-wp-each--greeting="context.list"
607
+
data-wp-each-key="context.greeting.id"
608
+
>
609
+
<lidata-wp-text="context.greeting.value"></li>
610
+
</template>
611
+
</ul>
612
+
```
613
+
614
+
For server-side rendered lists, another directive called `data-wp-each-child` ensures hydration works as expected. It should be placed in the server-side rendered elements.
0 commit comments