DEV Community

Sam Newby
Sam Newby

Posted on

Using Loops in Alpine.js

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.

Top comments (2)

Collapse
 
epsi profile image
E.R. Nurwijayadi

Dynamic Class Naming for Alpine.js Tabs Component Using x-for

I have made a more complex case using x-for.
There is limitation, but there is also workaround.

epsi-rns.gitlab.io/frontend/2020/1...

Dynamic Class Naming for Alpine.js Tabs Component Using x-for

Collapse
 
hyggedev profile image
Chris Hansen

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! :)