Skip to content

Instantly share code, notes, and snippets.

@harrytran998
Forked from IanVS/[lang]slash[slug].astro
Created July 10, 2022 15:01
Show Gist options
  • Save harrytran998/a56b7f663f64b3bc3de78d520af16c0d to your computer and use it in GitHub Desktop.
Save harrytran998/a56b7f663f64b3bc3de78d520af16c0d to your computer and use it in GitHub Desktop.
Redirecting i18n pages in Astro
---
import Layout from '../../layouts/MainLayout.astro';
import {getLanguageFromFilename, getSlugFromFilename} from '../../languages';
export async function getStaticPaths() {
/**
* This builds up a set of params using the filename (which is always in english) as the slug,
* and adds a redirect prop to the proper internationalized slug.
*/
function getRedirects(allPages) {
return allPages
.map(({ astro, url, file, ...page }) => {
const slug = getSlugFromFilename(file.pathname);
const locale = getLanguageFromFilename(file.pathname);
return {
params: {
locale,
slug
},
props: {
redirect: `/${locale}/${page.slug}`,
}
}
})
}
const allPages = Astro.fetchContent('../../data/docs/**/*.md');
const redirects = getRedirects(allPages);
const paths = allPages.map(({ astro, url, file, ...page }) => {
const locale = getLanguageFromFilename(file.pathname);
return {
params: {
locale: locale,
slug: page.slug
},
props: {
page: {
...page,
html: astro.html
}
}
}
})
return [...paths, ...redirects].filter(({ params }) => !!params.slug);
}
const { page, redirect } = Astro.props
---
{redirect
? <head><meta http-equiv="refresh" content={`0; url=${redirect}`}></head>
: <Layout content={page}>
{page.html}
</Layout>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment