Skip to content

Commit 0032eed

Browse files
committed
feat(blog): auto-detect cover.png when image not in frontmatter
1 parent 541187e commit 0032eed

1 file changed

Lines changed: 22 additions & 3 deletions

File tree

src/pages/[...slug].astro

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,40 @@
11
---
22
import type { GetStaticPaths } from 'astro';
3+
import type { ImageMetadata } from 'astro';
34
import { getCollection, render } from 'astro:content';
45
import PostLayout from '../layouts/PostLayout.astro';
56
67
export const getStaticPaths = (async () => {
78
const posts = await getCollection('blog');
9+
10+
// Import all cover images from blog directories
11+
const coverImages = import.meta.glob<{ default: ImageMetadata }>(
12+
'/src/content/blog/**/cover.png',
13+
{ eager: true }
14+
);
15+
816
return posts.map(post => {
917
// Extract just the slug from the path (e.g., "2024/slug-name" -> "slug-name")
1018
const slug = post.id.split('/').pop() || post.id;
19+
20+
// Try to find a default cover image if none specified in frontmatter
21+
let image = post.data.image;
22+
if (!image) {
23+
const coverPath = `/src/content/blog/${post.id}/cover.png`;
24+
const coverModule = coverImages[coverPath];
25+
if (coverModule) {
26+
image = coverModule.default;
27+
}
28+
}
29+
1130
return {
1231
params: { slug },
13-
props: { post, slug },
32+
props: { post, slug, image },
1433
};
1534
});
1635
}) satisfies GetStaticPaths;
1736
18-
const { post, slug } = Astro.props;
37+
const { post, slug, image } = Astro.props;
1938
const { Content } = await render(post);
2039
---
2140

@@ -25,7 +44,7 @@ const { Content } = await render(post);
2544
date={post.data.date}
2645
categories={post.data.categories}
2746
description={post.data.description}
28-
image={post.data.image}
47+
image={image}
2948
youtube={post.data.youtube}
3049
>
3150
<Content />

0 commit comments

Comments
 (0)