以前に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ライブラリを見つけた
これだと、
{ "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
の方法で取れる
別途、メリデメ整理してみる