i18next - 应用自定义格式

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

我有 2 个命名空间:

  • 第一个是全球性的,包含与业务相关的术语表
  • 第二个范围仅限于特定页面
// global ns
{
  "amendment": "amendment"
}

// page ns
{
  "action": "Enter your $t(global:amendment) below."
}

我在反应组件中的用例:

import React from 'react'
import { useTranslation } from 'react-i18next';

export function MyComponent() {
  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1>{t('amendment')}</h1>
      <p>{t('action')}</p>
    </div>
  )
}

我想使用大写转换来格式化

h1
元素中包含的文本。
实现这一目标的最佳方法是什么?

我已经考虑使用上下文并执行以下操作:

// global ns
{
  "amendment": "amendment",
  "amendment_uppercase": "Amendment"
}
import React from 'react'
import { useTranslation } from 'react-i18next';

export function MyComponent() {
  const { t, i18n } = useTranslation();

  return (
    <div>
      <h1>{t('amendment', {context: 'uppercase'})}</h1>
      <p>{t('action')}</p>
    </div>
  )
}

这里的问题是我必须复制所有翻译键,并且我有很多全局术语表。

javascript internationalization i18next
1个回答
1
投票

您有多种解决方案,其中之一是定义内置的 i18next 格式化程序并定义特定于页面的键,

header
需要大写。 因此,我定义了一个
header
键,它重复使用全局修正值,但应用了自定义格式化程序 (
ucwords
)

i18next.init(
  {
    lng: 'en', // if you're using a language detector, do not define the lng option
    resources: {
      en: {
        global: {
          amendment: 'amendment',
        },
        page: {
          header: '$t(global:amendment, ucwords)',
          action: 'Enter your $t(global:amendment) below.',
        },
      },
    },
    interpolation: {
      format: function (value, format, lng) {
        if (format === 'ucwords') return [value[0].toUpperCase(), value.slice(1)].join('');
        if (value instanceof Date) return moment(value).format(format);
        return value;
      },
    },
  },
  function (err, t) {
    // initialized and ready to go!
    document.getElementById('header').innerHTML = t('page:header');
    document.getElementById('action').innerHTML = t('page:action');
  }
);
<script src="https://unpkg.com/[email protected]/dist/umd/i18next.min.js"></script>
<h1 id="header"></h1>
<div id="action"></div>

© www.soinside.com 2019 - 2024. All rights reserved.