#Does Astro have something like a true slug, without the locale?

3 messages · Page 1 of 1 (latest)

sharp forum
#

With the recommended i18n directory structure, each post's slug contains its locale, e.g. '/en/my-post'. I only want the last part for a post's route, e.g. 'my-post'. How do I get that last part for an entry from a collection?

strange mangoBOT
#

Hi @sharp forum. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, Astro does provide a way to get the last part of a post's route, which is the true slug without the locale. This can be achieved by manipulating the auto-generated slug where getStaticPaths() is called, if you're using static site generation.

Here's an example of how you can do this:

export async function getStaticPaths() {
  const pages = await getCollection('pages');
  return pages.map(p => ({
    params: {
      slug: p.slug.slice(p.slug.indexOf('/') + 1), // remove /[locale]/ from start of slug
    },
    props: p,
  }))
}

In this example, p.slug.indexOf('/') + 1 finds the position of the first slash in the slug (which precedes the locale) and adds 1 to get the position of the start of the true slug. p.slug.slice() then removes the locale and the preceding slash from the slug.

This approach was suggested in a GitHub issue comment (https://github.com/withastro/astro/issues/7133) discussing a similar topic.

Remember that the slug is a URL-friendly property generated from the file id of each content entry when using type: 'content'. It's used to query the entry directly from your collection and is also useful when creating new pages and URLs from your content (source (https://docs.astro.build/en/guides/content-collections#defining-custom-slugs)).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: