Skip to content

Commit 4a5e806

Browse files
committed
Add dynamic breadcrumb schema to Head.astro
Introduces generation of structured data for breadcrumbs based on the current page's slug, improving SEO and navigation. The breadcrumb schema is injected as JSON-LD alongside the existing website schema.
1 parent 06ee43f commit 4a5e806

File tree

1 file changed

+38
-1
lines changed

1 file changed

+38
-1
lines changed

src/components/Head.astro

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
---
22
import Default from '@astrojs/starlight/components/Head.astro';
33
4+
const siteUrl = 'https://docs.sprites.dev';
45
const pageTitle = Astro.locals.starlightRoute?.entry?.data?.title ?? 'Sprites Documentation';
56
const ogImageUrl = `https://og-images.fly.dev/image?template=sprites&text=${encodeURIComponent(pageTitle)}`;
67
const slug = Astro.locals.starlightRoute?.slug ?? Astro.locals.starlightRoute?.id;
@@ -10,7 +11,41 @@ const websiteSchema = {
1011
'@context': 'https://schema.org',
1112
'@type': 'WebSite',
1213
name: 'Sprites Documentation',
13-
url: 'https://docs.sprites.dev',
14+
url: siteUrl,
15+
};
16+
17+
// Build breadcrumbs from URL path
18+
const formatSegment = (segment: string) =>
19+
segment
20+
.split('-')
21+
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
22+
.join(' ');
23+
24+
const pathSegments = (slug || '')
25+
.replace(/\.mdx?$/, '')
26+
.split('/')
27+
.filter(Boolean);
28+
29+
const breadcrumbItems = [
30+
{ name: 'Sprites Documentation', url: siteUrl },
31+
...pathSegments.slice(0, -1).map((segment, index) => ({
32+
name: formatSegment(segment),
33+
url: `${siteUrl}/${pathSegments.slice(0, index + 1).join('/')}/`,
34+
})),
35+
...(pathSegments.length > 0
36+
? [{ name: pageTitle, url: `${siteUrl}/${pathSegments.join('/')}/` }]
37+
: []),
38+
];
39+
40+
const breadcrumbSchema = {
41+
'@context': 'https://schema.org',
42+
'@type': 'BreadcrumbList',
43+
itemListElement: breadcrumbItems.map((item, index) => ({
44+
'@type': 'ListItem',
45+
position: index + 1,
46+
name: item.name,
47+
item: item.url,
48+
})),
1449
};
1550
---
1651

@@ -23,3 +58,5 @@ const websiteSchema = {
2358
{isHomePage && (
2459
<Fragment set:html={`<script type="application/ld+json">${JSON.stringify(websiteSchema)}</script>`} />
2560
)}
61+
62+
<Fragment set:html={`<script type="application/ld+json">${JSON.stringify(breadcrumbSchema)}</script>`} />

0 commit comments

Comments
 (0)