【问题标题】:Gatsby: load i18n content dynamically from contentfulGatsby:从内容动态加载 i18n 内容
【发布时间】:2020-10-07 23:46:56
【问题描述】:

我们有一个使用 Gatsby 且内容丰富的静态网站。现在我们要支持多语言,内容来自内容的本地化内容。我能够填充 graghql 查询:

query frontpageTeaser($lang: String) {
    contentfulFrontpage(node_locale: { eq: "zh-CN" }) {
      myArticalContent
      ...
    }
  } 

这个查询可以从contentful加载中文内容,如果改为node_locale: { eq: "en-US" },则可以加载英文。

现在的问题是:我们要支持语言切换,这样在切换语言时,graphql 会加载相应的本地化内容。

我们正在使用gatsby-plugin-react-i18next,它有这个很棒的功能:

在单个页面组件中支持多语言 url 路由。您不必创建单独的页面,例如 pages/en/index.js 或 pages/es/index.js。

http://localhost:8000/zh-CN/这样的页面确实会从本地/locales/zh-CN/translation.json加载中文,但是切换语言时如何加载本地化内容?

Graphql 似乎提供了page query,所以我添加了gatsby-node.js

exports.createPages = async function ({ actions, graphql }) {
  actions.createPage({
    path: '/zh-CN/',
    component: require.resolve(`./src/pages/index.js`),
    context: { lang: 'zh-CN' },
  })
}

并在页面上使用它:

export const query = graphql`
  query frontpageTeaser($lang: String) {
    contentfulFrontpage(node_locale: { eq: $lang }) {
      myArticalContent
    }
  } 
`

但它总是返回en。请帮助:)。谢谢。

【问题讨论】:

  • 不是这个用例,试试其他i18next插件,搜索教程

标签: graphql gatsby contentful


【解决方案1】:

这可能是一个复杂的开关。有一个示例项目使用另一个 CMS + Gatsby 顺利完成,here

代码库中需要指出的具体地方:

  • 配置您使用的语言环境,here
  • 取决于活动区域设置的动态链接,here
  • 整个应用程序了解活动区域设置的上下文,here
  • 实际在高阶组件Layouthere中实现locale context provider
  • gatsby-node.js 内部还有一些魔法,可以更新您已经在处理的内容!你可以找到,here

希望有帮助:)

【讨论】:

    【解决方案2】:

    在获得更好的解决方案之前,这个可行:

    // @todo gatsby plugin https://www.gatsbyjs.org/packages/gatsby-plugin-react-i18next/
    // this plugin provides current language `context.i18n.language`, which not know how to pass it to graphql page query.
    // This snippet moves it one-level up to `context.locale`.
    // @todo need to explore a better solution.
    exports.onCreatePage = ({ page, actions }) => {
      const { createPage, deletePage } = actions
    
      if (!page.context.locale) {
        const language = page.context.i18n.language
        const locale = language === 'en' ? 'en-US' : language
        deletePage(page)
    
        createPage({
          ...page,
          context: {
            ...page.context,
            locale,
          }
        })
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-29
      • 2018-07-23
      • 2011-06-14
      • 2014-02-23
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 2014-01-22
      • 2012-10-07
      相关资源
      最近更新 更多