To create a portfolio page layout that displays images from each subpage's Markdown file, you can use Astro's content collections feature along with the <Image /> component. Here's how you can approach this:
- First, set up a content collection for your portfolio items in
src/content/config.ts:
import { defineCollection, z } from "astro:content";
const portfolioCollection = defineCollection({
schema: ({ image }) => z.object({
title: z.string(),
cover: image(),
coverAlt: z.string(),
}),
});
export const collections = {
portfolio: portfolioCollection,
};
- In your portfolio item Markdown files, include the image information in the frontmatter:
---
title: "My Portfolio Item"
cover: "./item-cover.jpg"
coverAlt: "A description of the cover image"
---
This is the content of my portfolio item.
- Now, in your portfolio index page, you can use the
getCollection function to fetch all portfolio items and their associated images:
---
import { Image } from "astro:assets";
import { getCollection } from "astro:content";
const portfolioItems = await getCollection("portfolio");
---
{portfolioItems.map((item) => (
<div>
<Image src={item.data.cover} alt={item.data.coverAlt} />
<h2>
<a href={`/portfolio/${item.slug}`}>{item.data.title}</a>
</h2>
</div>
))}
This approach allows you to dynamically import and display images for each portfolio item on your index page. The <Image /> component will handle the optimization and processing of your images.