Skip to content

Instantly share code, notes, and snippets.

@IanVS
Created November 9, 2021 15:05
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save IanVS/4ae1145b1f4d0aa8f6bd7b16436addf6 to your computer and use it in GitHub Desktop.
Save IanVS/4ae1145b1f4d0aa8f6bd7b16436addf6 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