Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add internationalized dynamic routing example #28792

Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions examples/i18n-dynamic-routing/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
34 changes: 34 additions & 0 deletions examples/i18n-dynamic-routing/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env.local
.env.development.local
.env.test.local
.env.production.local

# vercel
.vercel
29 changes: 29 additions & 0 deletions examples/i18n-dynamic-routing/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# i18n dynamic routing

This example shows how to create internationalized dynamic pages using Next.js, dynamic routes, and the i18n routing feature. It shows how you can use the optional catch all routes feature with `getStaticPaths` and `getStaticProps` to create internationalized dynamic pages with a CMS.

For further documentation on this feature see the [Dynamic Routes docs](https://nextjs.org/docs/routing/dynamic-routes) and the [Internationalized Routing docs](https://nextjs.org/docs/advanced-features/i18n-routing).

## Preview

Preview the example live on [StackBlitz](http://stackblitz.com/):

[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/vercel/next.js/tree/canary/examples/i18n-dynamic-routing)

## Deploy your own

Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/i18n-dynamic-routing&project-name=i18n-dynamic-routing&repository-name=i18n-dynamic-routing)

## How to use

Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:

```bash
npx create-next-app --example i18n-dynamic-routing i18n-dynamic-routing-app
# or
yarn create next-app --example i18n-dynamic-routing i18n-dynamic-routing-app
```

Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).
33 changes: 33 additions & 0 deletions examples/i18n-dynamic-routing/lib/cms.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const db = {
pages: [
{
id: '1',
slug: { en: '/', es: '/' },
title: { en: 'Home', es: 'Inicio' },
},
{
id: '2',
slug: { en: '/about', es: '/acerca-de' },
title: { en: 'About', es: 'Acerca de' },
},
{
id: '3',
slug: {
en: '/products/phone-x/specs',
es: '/productos/phone-x/especificaciones',
},
title: {
en: 'Phone X - Tech Specs',
es: 'Phone X - Especificaciones Técnicas',
},
},
],
}

export function getPages({ locale }) {
return db.pages.filter((page) => page.slug[locale])
}

export function getPage({ locale, slug }) {
return db.pages.find((page) => page.slug[locale] === slug)
}
7 changes: 7 additions & 0 deletions examples/i18n-dynamic-routing/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
reactStrictMode: true,
i18n: {
locales: ['en', 'es'],
defaultLocale: 'en',
},
}
20 changes: 20 additions & 0 deletions examples/i18n-dynamic-routing/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "i18n-dynamic-routing",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "11.1.2",
"react": "17.0.2",
"react-dom": "17.0.2"
},
"devDependencies": {
"eslint": "7.32.0",
"eslint-config-next": "11.1.2"
}
}
103 changes: 103 additions & 0 deletions examples/i18n-dynamic-routing/pages/[[...slug]].js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { useRouter } from 'next/router'
import Link from 'next/link'
import { getPages, getPage } from '../lib/cms'

export default function Page({ links, page }) {
const { locales, locale, asPath } = useRouter()

return (
<div className="container">
<header>
{locales.map((l) => (
<Link key={`link-${l}`} locale={l} href="/">
<a className={l === locale ? 'active' : undefined}>{l}</a>
</Link>
))}
<hr />
{links.map((link) => (
<Link key={`link-${link.href}`} href={link.href}>
<a className={asPath === link.href ? 'active' : undefined}>
{link.label}
</a>
</Link>
))}
</header>
<main>
<h1>{page.title}</h1>
<h2>{page.slug}</h2>
</main>
<style jsx>{`
* {
color: black;
}

.container {
margin: 50px;
}

a {
display: inline-block;
padding: 10px 20px 10px 0;
text-decoration: none;
color: grey;
}

a.active {
font-weight: bold;
text-decoration: underline;
color: black;
}
`}</style>
</div>
)
}

export async function getStaticProps({ locale, params: { slug } }) {
const currentPage = await getPage({
slug: slug ? `/${slug.join('/')}` : '/',
locale,
})

const page = {
slug: currentPage.slug[locale],
title: currentPage.title[locale],
}

const pages = getPages({ locale })

const links = pages.map((page) => ({
label: page.title[locale],
href: page.slug[locale],
}))

return {
props: {
links,
page,
},
notFound: !!!page,
}
}

export async function getStaticPaths({ locales }) {
const paths = []

locales.forEach((locale) => {
getPages({ locale }).forEach((page) => {
const slug = page.slug[locale]
const [, ...slugParts] = slug.split('/')

paths.push({
locale,
params: {
slug: slug === '/' ? null : slugParts,
},
})
})
})

return {
paths: paths,
fallback: false,
}
}