So, let’s get started with our example, imagine we’ve got an array of developer profiles. We need to loop through that array and display the name and ID number of each developer. Alpine has the
x-for directive for us to conveniently use.
Here, we are using Alpine’s
x-for directive that I spoke about earlier, to loop through each developer in the developers array. Then inside each loop iteration we are displaying the developers name and ID number, using the
x-text directive on a div element.
x-text will update the
innerText of the element with the value provided. The crucial part of Alpine’s
x-for is that the directive is placed on a
<template> tag, otherwise it won’t work. You cannot place Alpine’s for loop on a
div or any other standard HTML element.
That is it for this post, I hope for those of you who are adopting Alpine in it’s early phase, are enjoying it as much as I am. More posts on Alpine.js, and it’s directives are coming, for now though, enjoy.
This post is from my blog: https://nwby.io/blog/using-loops-in-alpinejs/ - if you would like to head over there you will find more posts related to JS, Laravel, PHP, Go and other topics.
Top comments (2)
Dynamic Class Naming for Alpine.js Tabs Component Using x-for
I have made a more complex case using
There is limitation, but there is also workaround.
I just discoved AlpineJS. I'm trying to figure out how to loop through an object with images. I've tried many directives, and magic $ref, but nothing seems to work. Have any idea how to make this work? I'm trying to build a landing page with only Alpine, but I gotta make this work 😅 LMK if you have any suggestions! :)