Gemini notes
Posted on 29th May 2026 at 18:00 by Admin
To create an image gallery in Astro, you can dynamically loop over a directory of images using import.meta.glob() or use Content Collections for managing image metadata. Astro automatically optimizes these images using built-in <Image /> components.
Method 1: Using import.meta.glob (Automatic Directory Gallery)
This is the fastest method to instantly build a gallery from a folder of local files inside src/assets/images/.
---
import { Image } from 'astro:assets';
// 1. Grab all images in the directory
const images = import.meta.glob<{ default: ImageMetadata }>('/src/assets/images/*.{jpeg,jpg,png,webp}');
---
<div class="gallery-grid">
{Object.values(images).map(async (imageLoader) => {
const image = await imageLoader();
return (
<div class="gallery-item">
<Image
src={image.default}
alt="Gallery Image"
width={400}
height={300}
format="webp"
/>
</div>
);
})}
</div>
<style>
.gallery-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 1rem;
}
</style>
Method 2: Using Content Collections (Managed Image Galleries)
For larger projects where each image requires a title, description, or tags, Content Collections in src/content/ provide the best structure.
---
import { Image } from 'astro:assets';
import { getCollection } from 'astro:content';
// 1. Fetch images from your "gallery" collection
const galleryItems = await getCollection('gallery');
---
<div class="gallery-grid">
{galleryItems.map((item) => (
<div class="gallery-item">
<Image
src={item.data.image}
alt={item.data.altText}
width={400}
/>
<h3>{item.data.title}</h3>
</div>
))}
</div>