Cycles or Loops: x-for Alpine JS 9

We are going to learn about another very important feature of this type of framework, which is the use of for statements with which we can create a block of htm or html, a set of html based on the size of an array, for example here we have a three-dimensional array and we want each of these to be represented as a p with the p tag for paragraph, so instead of placing them one by one we simply use for, in this case x4, just as you can see, whose counterpart would be, if we take it to javascript, the for statement or cycle of a lifetime, that is, to iterate any element, so here the syntax is as follows, as if it were for each:

<div x-data="{todos:[ 'Sacar la basura', 'programar un rato', 'durar en el trabajo']}">
    <template x-for="t in todos">
        <p x-text="t"></p>
    </template>
</div>

We want to say that this element is not really the one we are placing up here, so we already placed the template, which is a special HTML tag, which is the template, which is a tag that is NOT rendered. It is useful for this type of scenarios, anyway, right now we are doing an experiment with this, that is what we have in the previous code.

As you can see, with the array we want to iterate, the x-for attribute is joined to iterate them.

In order to use logical attributes such as x-for and x-if, the template tag must be used exclusively, that is, you cannot place a DIV or similar as a container element for x-for or x-if, in case the internal element needs a container, you can place it as a container element for the x-for template:

<div x-data="{ todos:['Todo 1', 'Todo 2', 'Todo 3'] }">
   <ul>
       <template x-for="t in todos">
           <li x-text="t"></li>
       </template>
   </ul>
</div>

Another important point is that the x-for can only have one root element, in the following example the SPAN:

<div x-data="{todos:[ 'Sacar la basura', 'programar un rato', 'durar en el trabajo']}">
   <template x-for="t in todos">
       <p x-text="t"></p>
       <span>No se va a renderizar</span>
   </template>
</div>

- Andrés Cruz

En español

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.

!Courses from!

10$

On Udemy

There are 4d 19:28!


Udemy

!Courses from!

4$

In Academy

View courses

!Books from!

1$

See the books
¡Become an affiliate on Gumroad!