Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically import all images from a folder in Astro

I am working with Astro. The project uses quite a few images, and I want to simplify the way I currently add new images. My routes are like:

example.com/pictures/[collection]

( "[" and "]" stands for a dynamic route )

Allowing for example:

example.com/pictures/mixed-tecnique

example.com/pictures/graphite

example.com/pictures/acrylic


In the file pages/pictures/[collection].astro I want to do the following (or something similar):

---
import * as collections from "public/img/collections"

const { collection } = Astro.props
---

{collections[collection].map(imgSrc => <img src={imgSrc} />)}

So now, to have a new Collection route, I just have to create a new folder and drop the images there.

Is there any way to do something to reach the same result? Thanks in advance!!

like image 308
Genaro Bonavita Avatar asked Oct 18 '25 23:10

Genaro Bonavita


1 Answers

This is how I achieve:

---
const images = await Astro.glob("/src/assets/img/salon/*").then(files => {
  return files.map(file => file.default);
});
---

<div class="swiper">
  <!-- Additional required wrapper -->
  <div class="swiper-wrapper">
    <!-- Slides -->
    {
      images.map(image => (
        <div class="flex items-center justify-center swiper-slide">
          <img
            class="object-contain h-full rounded-lg"
            src={image}
            alt=""
            loading="lazy"
          />
        </div>
      ))
    }
  </div>
  ...
</div>

If you are using experimental assets feature:

{
  images.map(({ src /* width and height is also available */ }) => (
    <div class="flex items-center justify-center swiper-slide">
      <img
        class="object-contain h-full rounded-lg"
        src={src}
        alt=""
        loading="lazy"
      />
    </div>
  ))
}
like image 160
gokudesu Avatar answered Oct 20 '25 12:10

gokudesu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!