Table of Contents & Menu
Navigation

Alpine CSP x-for

Alpine CSP's x-for directive supports the following syntax patterns:

x-for="[value] in [value-provider]"

or

x-for="([value], [index]) in [value-provider]"

The [value-provider] in x-for must adhere to Alpine CSP's property access rules. It can reference a direct value or a function. When using a function, you must omit parentheses and cannot pass arguments.

Bad Example

This example will not work because arguments are passed to the getProducts method:

<template x-for="(product, index) in getProducts(selected)" :key="index">
    <span :class="getItemClasses"
          @click="goToItem>
    </span>
</template>

Correct usage involves referencing the function without parentheses:

    <template x-for="(product, index) in getProducts" :key="index">
            <span :class="getItemClasses"
                  @click="goToItem">
            </span>
    </template>

Directly referencing a property also works:

    <template x-for="(product, index) in products" :key="index">
            <span :class="getItemClasses"
                  @click="goToItem">
            </span>
    </template>

Within the template, the iteration value (e.g., product) and index are accessible in any called method:

goToItem() {
    return `${BASE_URL}/my/example/product/id/${this.product.id}`
}

Range Iteration Not Supported

Unlike standard Alpine, Alpine CSP does not support iterating over a range (e.g., x-for="i in 10"). You cannot use this syntax. For more details on standard Alpine's range iteration, refer to the Alpine.js documentation.