When I created the page to showcase all the pizza I’ve baked I had to load over 40 images. Importing them manually and displaying
in an <Image> component quickly became tedious. There had to be a quicker way.
And there was; the Astro.glob()
function!
The code below shows how to load all files inside a directory (make sure it only contains images, or edit the glob string pattern to your needs) and loop over them to render each inside a <Image> component.
Tailwind classes are used to show the images in a Pinterest-like fashion.
gallery.astro
---
import { Image } from 'astro:assets';
const imageFiles = await Astro.glob('./images/*');
---
<div class="columns-1 sm:columns-2 md:columns-3 lg:columns-4 gap-3 mb-5 mx-auto w-full px-4">
{
imageFiles.map((img) => (
<Image
src={img.default}
width="600"
alt="Photo of a pizza"
class="mb-3 w-full rounded"
/>
))
}
</div>
It is as easy as that! Give me a reaction to the right if this was helpful!