【问题标题】:How to change the slug in the url based on the language selected using gatsby-theme-i18n-react-i18next?如何根据使用 gatsby-theme-i18n-react-i18next 选择的语言更改 url 中的 slug?
【发布时间】:2021-08-01 19:30:20
【问题描述】:

我有一个使用 Gatsby 的项目,为了进行本地化,我使用了 gatsby-plugin-react-i18next 插件。如何根据所选语言更改 URL 中的 slug。例如,我在 pages 文件夹下有一个名为 product.js 的页面。在法语中,我希望页面为 https://www.example.com/fr/produit 而不是 https://www.example.com/product

【问题讨论】:

    标签: localization gatsby react-i18next


    【解决方案1】:

    您可以使用gatsby-plugin-react-i18next 插件获得bunch of options。在您的情况下,language 包含当前选择的语言。

    你有(至少)两个选择:

    • 使用来自gatsby-plugin-react-i18next 的公开链接组件:

      import {Link} from 'gatsby-plugin-react-i18next';
      
      const SpanishAboutLink = () => {
      
         const {language} = useI18next();
      
        <Link to="/about" language={language}>
           About page in Spanish
         </Link>
      };
      

      该插件包装了来自 Gatsby 的 Link 组件,添加了一个自定义道具 (language),该道具可以填充 useI18next 钩子的暴露状态。

    • 使用内置的Link(来自 Gatsby)并使用模板文字:

      const SpanishAboutLink = () => {
      
         const {language} = useI18next();
      
        <Link to=`{language}/about`>
           About page in the selected language
         </Link>
      };
      

      在这种方法中,您以与以前相同的方式获取当前语言,但您将其连接到 Link 组件以基于该参数创建 URL。

    在您的情况下,由于您要更改两个页面(productproduit)中的 slug,您需要同时使用页面查询和应用一个查询动态的以前的方法。例如:

    import * as React from 'react'
    import { graphql } from 'gatsby'
    
     const HomePage = ({data}) => {
          const {language} = useI18next();
     return (
        <div>
         <Link to={`${language}/${data.allYourPagesQuery.edges.node[0].slug}`}>
          {data.allYourPagesQuery.edges.node[0].title}
         </Link>
        </div>
      )
    }
    
    export const query = graphql`
      query HomePageQuery {
        allYourPagesQuery{
          edges {
            node {
             name
             slug
            }
          }
        }
      }
    `
    
    export default HomePage
    

    由于您的实施和数据源缺乏细节,我无法猜测您的查询应该是什么样子。但假设您有办法检索可用页面的titleslug,您可以执行上述sn-p 之类的操作。

    【讨论】:

    • 法语需要在pages下单独创建produit.js文件吗?
    • 理想情况下,是的。可以通过添加一些插件(i18 等)来调整 Gatsby 创建页面的方式。
    猜你喜欢
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    相关资源
    最近更新 更多