Alpine js : how to add image path in :src

How I can add the path of :src image in this loop.

<div x-data={ posts: {{ $posts}} }>
<template x-for="post in posts" :key="post.id">
<div>
**<img :src="images/posts/post.image" />**
*here I can't get image true path and show null*
<h3 x-text="post.title"></h3>
</div>
</template>
<div>

I’m guessing that you have a directory images/posts in your public folder that has all the image posts in it, and the post object has a key of image that is the file name for the image?

If that is the case then you will need to build out the string for the path. Having the colon at the start of the attribute means that you can use JavaScript inside the quotes so you will likely want your code to look like this:

<!-- Using template strings -->
<img :src="`images/posts/${post.image}`" />

<!-- Using old school string concatenation -->
<img :src="'images/posts/' + post.image" />
1 Like