🎠 The Magical Carousel: Looping with x-for in Alpine.js
Imagine you have a magical carousel at a fair. Each seat on the carousel holds one child, and the carousel spins, showing each child one by one. That’s exactly what x-for does in Alpine.js — it takes a list of things and shows each one, like seats on a carousel!
🎯 What You’ll Learn
- How to repeat things with
x-for - How to know which number seat you’re on (index)
- How to give each item a special name tag (key)
- How to loop through dictionaries (objects)
- How to count from 1 to any number (ranges)
🎪 The x-for Directive Basics
What is x-for?
Think of x-for like a copy machine. You give it one piece of paper (a template), and it makes copies for every item in your list!
The Simple Story
You have 3 favorite toys: a car, a ball, and a doll. Instead of writing each toy’s name three times, you tell Alpine:
“Here’s my list of toys. Show each one!”
Your First x-for
<div x-data="{ toys: ['Car', 'Ball', 'Doll'] }">
<template x-for="toy in toys">
<p x-text="toy"></p>
</template>
</div>
What happens?
- Alpine sees 3 toys
- It creates 3
<p>tags - Each
<p>shows one toy name
Result:
Car
Ball
Doll
🔑 Key Rules
- Always use
<template>tag - Write
x-for="item in items" - Put your content inside the template
graph TD A[🎒 Your List] --> B[template x-for] B --> C[Item 1] B --> D[Item 2] B --> E[Item 3]
🔢 Index and Key Access in Loops
What’s an Index?
Imagine standing in a line at school. Your position in the line is your index!
- First person = index 0
- Second person = index 1
- Third person = index 2
Why start at 0? Computers are a bit quirky — they start counting from zero!
Getting the Index
<div x-data="{ colors: ['Red', 'Blue', 'Green'] }">
<template x-for="(color, index) in colors">
<p>
<span x-text="index"></span>:
<span x-text="color"></span>
</p>
</template>
</div>
Result:
0: Red
1: Blue
2: Green
🏷️ What’s a Key?
When you have twins at school, the teacher needs name tags to tell them apart! The key is like a name tag for each item.
Why Use Keys?
Keys help Alpine remember which item is which, especially when the list changes!
Using Keys
<div x-data="{
pets: [
{ id: 1, name: 'Fluffy' },
{ id: 2, name: 'Buddy' },
{ id: 3, name: 'Max' }
]
}">
<template x-for="pet in pets" :key="pet.id">
<p x-text="pet.name"></p>
</template>
</div>
The :key="pet.id" tells Alpine: “Use the id as each pet’s name tag!”
graph TD A[🐕 pets array] --> B[Fluffy - key: 1] A --> C[Buddy - key: 2] A --> D[Max - key: 3]
💡 Pro Tip
Always use :key when your list items:
- Can be added or removed
- Can change order
- Have unique IDs
📦 Iterating Objects and Ranges
Looping Through Objects
An object is like a treasure box with labeled compartments. Each compartment has a name (key) and something inside (value).
{
name: 'Emma',
age: 8,
hobby: 'Drawing'
}
How to Loop Objects
First, turn the object into a list using Object.entries():
<div x-data="{
child: { name: 'Emma', age: 8, hobby: 'Drawing' }
}">
<template x-for="[key, value] in Object.entries(child)">
<p>
<strong x-text="key"></strong>:
<span x-text="value"></span>
</p>
</template>
</div>
Result:
name: Emma
age: 8
hobby: Drawing
🧮 Looping Through Ranges (Counting)
Want to count from 1 to 5? Use a range!
The Array Trick
<div x-data>
<template x-for="n in 5">
<p x-text="n"></p>
</template>
</div>
Result:
1
2
3
4
5
Magic! When you write x-for="n in 5", Alpine counts from 1 to 5!
Creating Stars ⭐
<div x-data="{ rating: 4 }">
<template x-for="star in rating">
<span>⭐</span>
</template>
</div>
Result: ⭐⭐⭐⭐
graph TD A[rating = 4] --> B[Loop 4 times] B --> C[⭐] B --> D[⭐] B --> E[⭐] B --> F[⭐]
🎨 Putting It All Together
Let’s build a simple todo list using everything we learned:
<div x-data="{
todos: [
{ id: 1, task: 'Eat breakfast', done: true },
{ id: 2, task: 'Go to school', done: true },
{ id: 3, task: 'Do homework', done: false }
]
}">
<h2>My To-Do List</h2>
<template x-for="(todo, index) in todos" :key="todo.id">
<div>
<span x-text="index + 1"></span>.
<span x-text="todo.task"></span>
<span x-show="todo.done">✅</span>
</div>
</template>
</div>
Result:
My To-Do List
1. Eat breakfast ✅
2. Go to school ✅
3. Do homework
📝 Quick Summary
| What | How | Example |
|---|---|---|
| Basic loop | x-for="item in items" |
Toys on carousel |
| With index | x-for="(item, i) in items" |
Line position |
| With key | :key="item.id" |
Name tags |
| Objects | Object.entries() |
Treasure box |
| Ranges | x-for="n in 5" |
Counting 1-5 |
🚀 You Did It!
You now know how to:
- ✅ Make Alpine repeat things with
x-for - ✅ Track position with index
- ✅ Use keys like name tags
- ✅ Loop through objects
- ✅ Count with ranges
Think of x-for as your magical copying assistant — give it a list, and it creates one copy for each item. Just like a carousel showing every rider, one by one! 🎠