pp-for

The pp-for directive allows you to dynamically render a list of elements by looping over an array or object. It acts similarly to JavaScript's forEach or map functions, and it's useful when displaying repeated data in the DOM.

Use Cases

  • Render a list of items from an array
  • Loop over objects or datasets to display structured content
  • Bind event handlers and attributes within each item

Syntax

  • pp-for="(item, idx) in items" — Loops over the array items, exposing item as the current element and idx as the index.
  • The <template> tag is used as the wrapper for the pp-for directive to prevent unnecessary DOM nodes and ensure optimal rendering.

Behavior

  • The loop is automatically re-evaluated whenever the underlying array changes.
  • All expressions inside {{ }}, as well as attributes using pp-bind or pp-bind-expr, are reprocessed for each item.
  • Event handlers inside the loop (e.g. onclick="...") can access the current index using i or idx.
  • Each iteration uses a cloned version of the template and is inserted after the <!-- pp-for --> comment marker.

Example Usage

Here's an example that loops over a list of users and displays their name and email. You can use idx to get the current index.

<div class="mb-2">
    <input type="text" name="name" placeholder="Name" oninput="userToAdd.name = this.value" value="{{ userToAdd.name }}" />
    <input type="email" name="email" placeholder="Email" oninput="userToAdd.email = this.value" value="{{ userToAdd.email }}" />
    <button onclick="addUser" class="btn btn-primary mt-2">Add User</button>
</div>

<template pp-for="(user, idx) in users">
    <div class="p-2 border rounded mb-2">
        <p>#{{ idx + 1 }} - {{ user.name }}</p>
        <p>Email: {{ user.email }}</p>
        <button onclick="removeUser('{{ idx }}')" class="btn btn-error btn-sm mt-1">Remove</button>
    </div>
</template>

<script>
    pphp.state('users', [{
            name: 'Alice',
            email: 'alice@example.com'
        },
        {
            name: 'Bob',
            email: 'bob@example.com'
        }
    ]);

    export const addUser = () => {
        users.push({
            name: userToAdd.name,
            email: userToAdd.email
        });

        userToAdd.name = '';
        userToAdd.email = '';
    };

    export const removeUser = (index) => {
        users.splice(Number(index), 1);
        pphp.sync('users');
    };
</script>

This example demonstrates how the pp-for directive dynamically renders user cards and allows removal of individual entries using the index.