astro-headless-ui icon indicating copy to clipboard operation
astro-headless-ui copied to clipboard

Breadcrumbs: Page title

Open simplerethink opened this issue 1 year ago • 3 comments

For Breadcrumbs, how can I have the output text be the page title, rather than the slug?

I still want a link, but the links should be page titles.

simplerethink avatar Sep 16 '24 19:09 simplerethink

Hello :wave:

Where is your title defined? Is it inside the frontmatter of a Content Collection?

You can use slots to override the default HTML for the Breadcrumbs. I haven't tested this, but it should look something like this:

---
import { getEntry } from 'astro:content';

function getCollectionIdFromURL(href: string) {
	// ...
}
---

<Breadcrumb>
    {async ({ href, text }) => {
    	const id = getCollectionIdFromURL(href)
    	
    	// If URL is a content collection entry
    	if (id) {
    		const entry = getEntry('blog', id)
    		return <a {href}>{entry.data.title}</a>
    	} 
    	
    	return <a {href}>{text }</a>
    }}
</Breadcrumb>

The getCollectionIdFromURL function should convert the href of the current page (ex: website/blog/my-favorite-color) to the slug/id of a collection entry inside src/content and return false if there is no entry.

BryceRussell avatar Sep 16 '24 21:09 BryceRussell

Yes, title is in the frontmatter of a collection.

getCollectionIdFromURL is probably a bit over my head at this point, but I'll give it a shot.

Thank you for the feedback!

simplerethink avatar Sep 17 '24 12:09 simplerethink

I think I have a different solution that works for my current needs.

---
const { title } = Astro.props;

function camelCaseString(str) {
  return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase().trim();
}
---

<Breadcrumbs>
    {url => (<a href={url.href}>{camelCaseString(url.text)}</a><span>&gt;</span>)}
    <active slot="active">{url => <span>{title}</span>}</active>
</Breadcrumbs>

simplerethink avatar Sep 17 '24 12:09 simplerethink