/ #alpinejs #javascript 

Alpine.js `x-for` a number of iterations (n times)

Alpine.js falls back to JavaScript to allow you to iterate a set number of times.

For example if I want to create 4 lines on a page I can use the following.

<div x-data>
  <template x-for="_ in Array.from({ length: 4 })">
    <hr>
  </template>
</div>

You can see all the examples at Alpine.js Playground - x-for n times.

Table of Contents

Different ways to create an array of n length in JavaScript

If you’re coming from Vue, you might expect the following to work, but it doesn’t work.

<div x-data>
  <template x-for="_ in new Array(4)">
    <hr>
  </template>
</div>

Alpine.js v2 currently only loops through arrays using .forEach so using new Array(4) means we hit a quirk of that method: forEach goes through items and new Array(4), despite having length 4, has no items.

The solution here is to .fill the array, for example:

<div x-data>
  <template x-for="_ in new Array(4).fill(null)">
    <hr>
  </template>
</div>

Or even .fill(undefined)

<div x-data>
  <template x-for="_ in new Array(4).fill(undefined)">
    <hr>
  </template>
</div>

Which both work as well as the introduction example:

<div x-data>
  <template x-for="_ in Array.from({ length: 4 })">
    <hr>
  </template>
</div>

You can see all the examples at Alpine.js Playground - x-for n times.

That’s it for this post, you can check out the Alpine.js tag on Code with Hugo for more in-depth Alpine.js guides.

If you’re interested in Alpine.js, Subscribe to Alpine.js Weekly. A free, once–weekly email roundup of Alpine.js news and articles.

Photo by Brandon Mowinkel on Unsplash

Author

Hugo Di Francesco

Co-author of "Professional JavaScript" with Packt. He runs the Code with Hugo website helping over 100,000 developers every month and holds an MEng in Mathematical Computation from University College London (UCL). He has used JavaScript extensively to create scalable and performant platforms at companies such as Canon and Elsevier.

Interested in Alpine.js?

Subscribe to Alpine.js Weekly A free, once–weekly email roundup of Alpine.js news and articles