To manage the situation where your route structure doesn't match the id structure of your content collection, you have a few options. The most straightforward approach is to modify your link generation to exclude the category from the URL. Here's how you can do it:
- Modify the link generation:
Instead of using the full id in your link, you can split it and use only the last part:
<a
href={`/experiences/experience/${id.split('/').pop()}`}
class="flex items-center gap-2 transition hover:underline"
>
This will remove the category from the URL, making it compatible with your /experiences/experience/[id].astro route.
- Handle the routing in your
[id].astro file:
In your /experiences/experience/[id].astro file, you'll need to fetch the correct experience based on the id parameter. Here's an example of how you might do this:
---
import { getCollection } from 'astro:content';
export async function getStaticPaths() {
const experiences = await getCollection('experiences');
return experiences.map(experience => ({
params: { id: experience.id.split('/').pop() },
props: { experience },
}));
}
const { experience } = Astro.props;
---
<!-- Your experience page template here -->
This approach generates routes for all experiences, using only the last part of the id (the filename without the category) as the URL parameter.
- Alternatively, use dynamic routing:
If you're using server-side rendering (SSR), you can handle this dynamically:
---
import { getEntry } from 'astro:content';
const { id } = Astro.params;
const experience = await getEntry('experiences', id);
if (!experience) {
return Astro.redirect('/404');
}
---
<!-- Your experience page template here -->