Learn extra at:
<div x-data="{
albums: [],
fetchAlbums() {
fetch('/albums')
.then(response => response.json())
.then(information => {
this.albums = information;
});
}
}">
<ul>
<template x-for="album in albums":key="album.id">
<li x-text="album.identify"></li>
</template>
</ul>
<button @click on="fetchAlbums()">Load Albums</button>
</div>
For this one, x-data
is the attribute that creates the Alpine part and it defines the required client-side state (albums) and a bespoke technique for fetching the info from the server (fetchAlbums
). Discover the view contained in the unordered record (the <ul>
) makes use of some additional Alpine attributes (x-for
and x-text
) to carry out an iteration and describe easy methods to output the state to the display screen.
The state is held in x-data
attributes and Alpine’s job is to take that state and make sure the UI displays it routinely. The info from the server, as quickly as it’s acquired by Alpine’s fetch name, can be rendered by the view. Right here’s what the info coming again for this instance would possibly appear to be:
[
{ "id": 1, "name": "The Dark Side of the Moon" },
{ "id": 2, "name": "Kind of Blue" },
{ "id": 3, "name": "Abbey Road" },
{ "id": 4, "name": "Rumours" }
]
Once we evaluate HTMX information with Alpine’s, the distinction between REST (the place the illustration of the state, that means the view, is transferred) and REST-like (as generally applied with JSON APIs) could be very clear. HTMX needs to ship chunks of the precise view containing the state, and Alpine needs to ship chunks of an information format (JSON) after which remodel it right into a view on the shopper.