-
-
Save harrytran998/a56b7f663f64b3bc3de78d520af16c0d to your computer and use it in GitHub Desktop.
Redirecting i18n pages in Astro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
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