UGA Boxxx

つぶやきの延長のつもりで、知ったこと思ったこと書いてます

【Next.js】next-translateでJSON arrayは使えるのか

以前にnext-translateを使ってNext.jsアプリの翻訳を行った

【Next.js】next-translateでNext.jsページを翻訳する - UGA Boxxx
【Next.js】next-translateのbuild step以外でNext.jsページを翻訳する - UGA Boxxx

このnext-translateで用意するnamespaces filesの中でJSON arrayが使えるか調査

namespaces files

namespaces filesというのは、localesディレクトリ配下に言語毎に配置するjsonファイルのこと

/locales

.
├── ca
│   ├── common.json
│   └── home.json
├── en
│   ├── common.json
│   └── home.json
└── es
    ├── common.json
    └── home.json

中身はこのような形で記述する

{
  "title": "Hello world",
  "variable-example": "Using a variable {{count}}"
}

使用する時はこのように実装する

t("common:title")

このときに次のような JSON arrayが使えるかどうか

{
  "title": ["Hello", "world"]
}

できれば、"common:title.0"のようにして、戻り値をstringで受け取りたい

結論:JSON arrayは使えるが、stringではなくobjectで受け取る

JSON arrayも使えることはREADMEにも書いてあった

{
  "array-example": [
    { "example": "Example {{count}}" },
    { "another-example": "Another example {{count}}" }
  ]
}

その場合は、returnObjects: trueをオプションとして渡してあげる必要があるとのこと

t('namespace:array-example', { count: 1 }, { returnObjects: true })
/*
[
  { "example": "Example 1" },
  { "another-example": "Another example 1" }
]
*/

ただ、"common:title.0"のようにはできなかった

i18next.js

この調査中にi18next.jsという国際化対応JSライブラリを見つけた

www.i18next.com

これだと、

{
      "arrayJoin": [
        "line1",
        "line2",
        "line3"
      ],
      "arrayJoinWithInterpolation": [
        "you",
        "can",
        "{{myVar}}"
      ],
      "arrayOfObjects": [
        { "name": "tom" },
        { "name": "steve" }
      ]
}

このような形でJSON arrayが取得できるみたい

i18next.t('arrayJoin', { joinArrays: '+' });
// -> "line1+line2+line3"

i18next.t('arrayJoinWithInterpolation', { myVar: 'interpolate', joinArrays: ' ' });
// -> "you can interpolate"

i18next.t('arrayOfObjects.0.name');
// -> "tom"

これだと、希望通りarrayOfObjects.0.nameの方法で取れる

別途、メリデメ整理してみる