I was going through the new guide at https://docs.astro.build/en/guides/assets/ today, trying to migrate one of my projects to the new version.
One thing I wasn't able to figure out myself is how to use image assets specified in the frontmatter of an .mdx file.
For example, I might want to specify a thumbnail image in the frontmatter of each blog post's .mdx file.
---
title: 'Blog Post Title'
thumbnail: '../../assets/images/blog_post_1.png'
---
Mollit proident eiusmod mollit aute est pariatur duis eu enim in voluptate. Officia ipsum culpa officia eiusmod. Id voluptate consequat sit ut tempor id. Proident et nostrud consequat proident sint.
Now, let's say I want to display a list of all blog posts with their thumbnails. How do I (dynamically) import the image so I can provide it to the src attribute of the Image component?
Using a dynamic import doesn't work because Vite doesn't permit fully dynamic paths (e.g. you have to provide the file ending, ...).
posts/index.astro
---
import { Image} from 'astro:assets';
const posts: BlogPost[] = await getCollection('posts');
---
<div>
{
posts.map((post: Post) => {
return (
<div>
<Image src={post.data.thumbnail} alt="..." ????? />
</div>
);
})
}
</div>
I have also tried using
src={`/_astro/images/posts/${post.data.thumbnail}`}
without any success.
I'm assuming there is a correct way to do this since the official guide uses the example of a cover image inside the schema definition. Maybe, the Assets guide on the website could be expanded with an example of how to use frontmatter images inside an .astro file.
const blogCollection = defineCollection({
schema: z.object({
title: z.string(),
cover: image().refine((img) => img.width >= 1080, {message: 'Cover image must be at least 1080 pixels wide!'}),
}),
});
Any help would be greatly appreciated!