feat: automatically generate Open Graph cards

This commit is contained in:
radishzzz 2025-03-13 05:00:18 +00:00
parent 9b9bdb2811
commit a556a622ab
14 changed files with 59 additions and 30 deletions

View file

@ -2,6 +2,7 @@
import Waline from '@/components/Comments/Waline.astro'
import Layout from '@/layouts/Layout.astro'
import { checkSlugDuplication } from '@/utils/content'
import { generateDescription } from '@/utils/description'
import { generateMultiLangPostPaths } from '@/utils/i18n/route'
import { getCollection } from 'astro:content'
@ -17,10 +18,15 @@ export async function getStaticPaths() {
}
const { post } = Astro.props
const description = generateDescription(post)
const { Content, remarkPluginFrontmatter } = await post.render()
---
<Layout>
<Layout
postTitle={post.data.title}
postDescription={description}
postSlug={post.slug}
>
<article>
<h1>{post.data.title}</h1>
<time>

View file

@ -1,16 +1,23 @@
import { themeConfig } from '@/config'
import { generateDescription } from '@/utils/description'
import { OGImageRoute } from 'astro-og-canvas'
import { getCollection } from 'astro:content'
// eslint-disable-next-line antfu/no-top-level-await
const blogEntries = await getCollection('posts')
// 确定favicon路径是完整URL还是相对路径
const logoPath = themeConfig.site.favicon.startsWith('http')
? themeConfig.site.favicon
: `./public${themeConfig.site.favicon}`
// Convert to page data objects
const pages = Object.fromEntries(
blogEntries.map(({ slug, data }) => [
slug,
blogEntries.map(post => [
post.slug,
{
title: data.title,
description: data.description || '',
title: post.data.title,
description: post.data.description || generateDescription(post),
},
]),
)
@ -22,7 +29,27 @@ export const { getStaticPaths, GET } = OGImageRoute({
getImageOptions: (_path, page) => ({
title: page.title,
description: page.description,
border: { width: 10 },
padding: 40,
logo: {
path: logoPath,
size: [80],
},
font: {
title: {
families: ['Noto Sans SC'],
weight: 'Bold',
color: [34, 33, 36],
lineHeight: 1.5,
},
description: {
families: ['Noto Sans SC'],
color: [72, 71, 74],
lineHeight: 1.5,
},
},
fonts: [
'https://raw.githubusercontent.com/notofonts/noto-cjk/main/Sans/SubsetOTF/SC/NotoSansSC-Bold.otf',
'https://raw.githubusercontent.com/notofonts/noto-cjk/main/Sans/SubsetOTF/SC/NotoSansSC-Regular.otf',
],
bgGradient: [[242, 241, 245]],
}),
})