I am running a for loop with Alpine.js. I am using the Nunjucks template engine.
I have an array with three items called items
Is it possible to inject the item variable in the src attribute of the img tag? See code below.
<div x-data="{items: ['first-image.png','second-image.png','third-image.png'], active: 0}">
<div class="snap overflow-auto relative flex-no-wrap flex transition-all" x-ref="slider"
x-on:scroll.debounce="active = Math.round($event.target.scrollLeft / ($event.target.scrollWidth / items.length))">
<template x-for="(item,index) in items" :key="index">
<div class="w-full flex-shrink-0 flex items-center justify-center">
<img src="`../assets/images/favicon/${item}`" alt="" style="height:550px">
</div>
</template>
</div>
Definitely possible, what you're looking for is the x-bind
directive.
You can "bind" a value from your Alpine.js component state to the src
attribute using x-bind:src="someValue"
or :src=""
in shorthand
So you can do:
<img x-bind:src="`../assets/images/favicon/${item}`" alt="" style="height:550px">