我有一个多语言站点,需要根据每个页面的语言设置 HTML lang 属性。
我尝试在上下文中传递值,但在页面更改时不会更新。
这里是当前代码:
import Document, { Html, Head, Main, NextScript } from 'next/document'
import GlobalContext , {eLanguage }from '../components/GlobalContext' //my global context
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const initialProps = await Document.getInitialProps(ctx)
return { ...initialProps }
}
static contextType = GlobalContext;
render() {
console.debug('Started')
console.debug('language:'+ this.context.language)
return (
<Html lang={eLanguage[this.context.language]}> //if the first page loaded as lang 'en' it sets 'en' and apply to all other pages.
<Head>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
}
更新:可以从页面路由推断出每个页面的语言
原文由 MiguelSlv 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用文档对象,可以像这样设置 lang 属性:
这个 lang 属性不会在初始 html 上设置,在页面被水合之前,但仍会通过 chrome“hreflang”审核检查。