如何使用i18n来盖茨比?

问题描述 投票:2回答:1

我的gatsby网站翻译有问题。

我正在使用i18n插件进行翻译,但如果我在我的index.jsx中放入两个FormattedMessage标签,它会破坏我的index.jsx

我可以在谷歌找到我的问题,但我无法弄清楚如何解决它。

我的index.jsx

import React from 'react'
import { FormattedMessage } from 'react-intl'

import Layout from '../components/Layout'


const IndexPage = ({ pathContext: { locale } }) => (
  <Layout locale={locale}>
    <FormattedMessage id="hello" />
    <FormattedMessage id="hello" />
  </Layout>
)

export default IndexPage

和我的布局:

import React from 'react'
import PropTypes from 'prop-types'
import Helmet from 'react-helmet'
import { StaticQuery, graphql } from 'gatsby'

import Header from './header'
import './layout.css'

import { IntlProvider, addLocaleData } from 'react-intl'

// Locale data
import enData from 'react-intl/locale-data/en'
import ptData from 'react-intl/locale-data/pt'
import esData from 'react-intl/locale-data/es'

// Messages
import en from '../i18n/en.json'
import pt from '../i18n/pt.json'
import es from '../i18n/es.json'

const messages = { en, pt, es }

addLocaleData([...enData, ...ptData, ...esData])

const Layout = ({ locale, children }) => (
  <StaticQuery
    query={graphql`
      query SiteTitleQuery {
        site {
          siteMetadata {
            title
          }
        }
      }
    `}
    render={data => (
      <>
        <Helmet
          title={data.site.siteMetadata.title}
          meta={[
            { name: 'description', content: 'Sample' },
            { name: 'keywords', content: 'sample, something' },
          ]}
        >
          <html lang="en" />
        </Helmet>
        <Header lang="/^\/eng/" />
        <div
          style={{
            margin: '0 auto',
            maxWidth: 960,
            padding: '0px 1.0875rem 1.45rem',
            paddingTop: 0,
          }}
        >
          <IntlProvider locale={locale} messages={messages[locale]}>
            {children}
          </IntlProvider>
        </div>
      </>
    )}
  />
)

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout

我希望你不能帮我使用多个FormattedMessage标签进行翻译,谢谢。

reactjs gatsby i18next
1个回答
1
投票

也许对你来说不是一个有效的解决方案但是..你尝试过gatsby-plugin-i18next吗?我与gatsbyjs的第一个项目是一个关于语言的噩梦处理,直到我找到它。在我看来,它的效果非常好。你必须用npm / yarn安装并配置一点。您可以删除包装器IntlProvider,您可以在任何地方(页面/模板或组件)进行翻译。

这里和您的代码中提取的示例(英语和西班牙语)。该插件负责处理URL,将/ es&/ en放在每个页面/模板中:

SRC /页/ index.jsx

import React from 'react'; 
import { I18n } from 'react-i18next'; 
import { withI18next } from 'gatsby-plugin-i18next';
import Layout from '../components/index'

const IndexPage = props => (<I18n>{t => (
    <Layout{...props}>
        <p>{t('hello')}</p>
        <p>{t('hello')}</p>
    </Layout>
)}</I18n>);

export const query = graphql`
query($lng: String!){
    locales: allLocale(filter: { lng: { eq:$lng }, ns: { eq: "messages" } }) {
      ...TranslationFragment
    }
  }
`;

export default withI18next()(IndexPage);

SRC /组件/ index.jsx

请注意,您还必须更改头盔。我翻译元数据是为了展示如何在组件中进行翻译(而不是页面都不是模板)。

import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import { Head } from 'gatsby-plugin-i18next';
import { StaticQuery, graphql } from 'gatsby'

import Header from './header'
import './layout.css'

const Layout = ({children, t }) => (
  <StaticQuery
    query={graphql`
      query SiteTitleQuery {
        site {
          siteMetadata {
            title
          }
        }
      }
    `}
    render={data => (
      <>
        <Head hreflang>
           <title>{data.site.siteMetadata.title}</title>
           <meta name="description" content="{t('metaDescription')}" />
           <meta name="keywords" content="{t('metaKeywords')}" />
        </Head>
        <Header lang="/^\/eng/" />
        <div
          style={{
            margin: '0 auto',
            maxWidth: 960,
            padding: '0px 1.0875rem 1.45rem',
            paddingTop: 0,
          }}
        >
        {children}
        </div>
      </>
    )}
  />
)

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default translate()(Layout)

gatsby-config.js您只能在开发时调试插件;)

const defaultLanguage = "en";
const languages: ["en", "es"];
const siteUrl: "https://domain-where-the-gatsby-are-published.com/",

module.exports = {
    ...,
    plugins: [
        ...,
        {
            resolve: `gatsby-plugin-i18next`,
            options: {
                availableLngs: languages,
                fallbackLng: defaultLanguage,
                debug: process.env.NODE_ENV === 'development',
                siteUrl
            },
        }
    ],
}

本地/ EN / messages.json

{
  "hello": "Hi!",
  "metaDescription": "Sample page with i18n translations",
  "metaKeywords": "i18n, gatsbyjs, english"
}

本地/ ES / messages.json

{
  "hello": "Hola!",
  "metaDescription": "Página de ejemplo con traducciones i18n",
  "metaKeywords": "i18n, gatsbyjs, spanish"
}

作为额外的评论:

  • 请记住将从gatsby导入的所有链接更改为gatsby-plugin-i18next
  • 您必须在每个页面/模板中注入graphql查询
  • 您可以看到starter的代码,看看如何在语言之间创建切换器
© www.soinside.com 2019 - 2024. All rights reserved.