Using Loops in Alpine.js

Sam Newby - May 4 '20 - - Dev Community

Alpine.js is a great, new framework inspired heavily by Vue.js. It is great for adding small snippets of JavaScript behaviour to your markup, when and where you need it.

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.

Alt Text

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.

. . . . . . . . . . . .
Terabox Video Player