Alpine’s x-for
is just like Vue’s v-for
. We can create elements by loop directly in HTML.
Version
Alpine 3.9
x-for
Use x-for
with x-data
to create <li>
by loop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://unpkg.com/alpinejs" defer></script>
<title>Alpine</title>
</head>
<body x-data="{ colors: ['Red', 'Green', 'Blue']}">
<ul>
<template x-for="x in colors">
<li x-text="x" />
</template>
</ul>
</body>
</html>
Line 9
<body x-data="{ colors: ['Red', 'Green', 'Blue']}">
<ul>
<template x-for="x in colors">
<li x-text="x" />
</template>
</ul>
</body>
x-for
must be declared on a<template>
- The
<template>
must have only one root element
Conclusion
x-for
must be used with<template>
. This is considerably different from Vue