In this tutorial we will see how to use for loop in alpine js, x-for loop with number, alpinjs loop through array, x-for loop index iteration, alpinejs x-for loop with associative arrays (key value pair) example with AlpineJS 3.
Example 1
Alpinejs simple x-for loop using number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Alpine Js x-for Loop</title>
<script
defer
src="https://unpkg.com/[email protected]/dist/cdn.min.js"
></script>
</head>
<body>
<ul x-data="{ numbers: [1, 2, 3] }">
<template x-for="number in numbers">
<li x-text="number"></li>
</template>
</ul>
</body>
</html>
Example 2
Alpinejs x-for loop index iteration.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Alpine Js x-for Loop</title>
<script
defer
src="https://unpkg.com/[email protected]/dist/cdn.min.js"
></script>
</head>
<body>
<div x-data="{ brands: ['Amazon', 'Apple', 'Google','Microsoft'] }">
<template x-for="(brand, index) in brands">
<div><span x-text="index"></span>:<span x-text="brand"></span></div>
</template>
</div>
</body>
</html>
Example 3
Alpinejs for loop with Iterating over a range.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Alpine Js x-for Loop</title>
<script
defer
src="https://unpkg.com/[email protected]/dist/cdn.min.js"
></script>
</head>
<body style="margin: 200px;">
<ul x-data>
<template x-for="i in 10">
<li x-text="i"></li>
</template>
</ul>
</body>
</html>
Example 4
Alpinejs x-for loop with associative arrays key value pair.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Alpine Js x-for Loop</title>
<script
defer
src="https://unpkg.com/[email protected]/dist/cdn.min.js"
></script>
</head>
<body>
<ul
x-data="{ people: [
{ id: 1, name: 'Jhon' },
{ id: 2, name: 'nike' },
{ id: 3, name: 'sam' },
]}"
>
<template x-for="person in people" :key="person.id">
<li x-text="person.name"></li>
</template>
</ul>
</body>
</html>
You can also clean alpinejs code to writer in bottom.
<ul x-data="employee">
<template x-for="person in people" :key="person.id">
<li x-text="person.name"></li>
</template>
</ul>
<script>
document.addEventListener('alpine:init', () => {
Alpine.data('employee', () => ({
people: [
{ id: 1, name: 'Jhon' },
{ id: 2, name: 'nike' },
{ id: 3, name: 'sam' },
],
}));
});
</script>