How translate the slugs in my web pages?
Thu, Jan 12, 2023
I wanted to make a blog and I was wondering how to internationalise my site including its urls. The challenge is to make the pages are created at build time are assigned to each of its translated slugs.
This is my solution:
1. Create a mdx file for each language, for example:
data/blog/translate-the-slugs/translate-the-slugs.en.mdx
data/blog/translate-the-slugs/translate-the-slugs.es.mdx
data/blog/translate-the-slugs/translate-the-slugs.gl.mdx
2. Inside each mdx file, the important thigs are:
3. With getStaticPaths we created the pages for each language:
In my case I create different pages for each tag and category, but you can create the pages you want.
4. With getStaticProps we get the data of the mdx file:
When getStaticPaths is executed, it passes the locale to getStaticProps, in this moment we have the category, slug and locale, so we can get the data of the mdx file.
4.1. Get the data of the mdx file with help from gray-matter and fs:
We need create functions to help us to get the data of the mdx file.
4.2. Serialize the mdx file with help from @next-mdx-remote/serialize:
import { serialize as sz } from 'next-mdx-remote/serialize';/** * @description Serialize MDX file with Code Hike. * * @example * serialize('# Hello World'); * returns { content: '...', meta: {...} } * * @param {string} mdx - MDX file. * @returns {Object} - Object with MDX content and meta data. */export const serialize = (mdx: string) => sz(mdx, { mdxOptions: { remarkPlugins: [[remarkCodeHike, { autoImport: false, theme }]], useDynamicImport: true, }, });
4.3. Get the data finally into your component for the presentation layer.
You can see the result by looking at the url of this post and changing the language in settings and looking at the same post again.