#How to set html lang dynamically

1 messages · Page 1 of 1 (latest)

twin isle
#

I want to set my html lang attribute dynamically based on params.

slow hatchBOT
#

Hi @twin isle. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can set the lang attribute of your HTML dynamically in Next.js by using the params object in your page or layout component. This is particularly useful when you're implementing internationalization (i18n) in your Next.js application.

Here's an example of how you can do this:

export default function Root({ children, params }) {
 return (
 <html lang={params.lang}>
 <body>{children}</body>
 </html>
 )
}

In the above example, params.lang will be the value of the lang attribute in your HTML tag. This value can be dynamically set based on the current locale of your application.

To generate static routes for a given set of locales, you can use generateStaticParams function like this:

export async function generateStaticParams() {
 return [{ lang: 'en-US' }, { lang: 'de' }]
}

In this example, generateStaticParams returns an array of objects, each containing a lang property. This property will be used as the value of params.lang in your page or layout component.

Remember to nest all special files inside app/ under app/[lang]. This enables the Next.js router to dynamically handle different locales in the route, and forward the lang parameter to every layout and page.

For more information, you can refer to the Next.js documentation on internationalization (https://nextjs.org/docs/pages/building-your-application/routing/internationalization#search-engine-optimization) and static generation (https://nextjs.org/docs/app/building-your-application/routing/internationalization#static-generation).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@twin isle kapa.ai is still learning and improving, please let us know how it did by reacting below

twin isle
#

@slow hatch I am using app router on next 14.2 and <html lang attribute is on root layout... the dynamic params will be wmpty there...

#

<@&1089670008898080870> I am using app router on next 14.2 and <html lang attribute is on root layout... the dynamic params will be wmpty there...