LoginSignup
0
0

いろいろ翻訳、JSもね。"UxTranslator"

Last updated at Posted at 2023-12-16

Symfony Component Advent Calendar 2023の17日目の記事です。

いろいろ翻訳、JSもね。"UxTranslator"

UxTranslatorは、Translationコンポーネントで使った翻訳ファイルを使って、フロントエンドも翻訳してしまうSymfony UXコンポーネントです。

インストール

composer require symfony/ux-translator

使い方

Translationで用意した翻訳ファイルtranslations/***.ja.yamlを使いますが、こちらはIDでのみ取得できるようです。

translations/message.ja.yaml
apple: "これはりんごです。"
pear: "これはなしです。"
hello: "こんにちは {name}さん"

インストール時、assets/translator.jsというファイルがあります。これを使って翻訳ができます。

翻訳時、IDは大文字化され、.やネストは_に変わります。

apple: "これはりんごです。"
gender:
    male: "男性"
    female: "女性"
app.name: "アプリ名"

↑の場合は

APPLE
GENDER_MALE
GENDER_FEMALE
APP_NAME

となります。

assets/sample.js

import {trans, setLocale, APPLE, PEAR} from './translator.js'

setLocale('ja'); // ロケールをjaに設定

console.log(trans(APPLE)); // これはりんごです。
console.log(trans(PEAR)); // これはなしです。
console.log(trans(HELLO, {name: "すみだ"}); // こんにちは すみださん

翻訳ファイルの更新

翻訳ファイルですが、var/translator/index.jsに保存されています。つまり、translations/にあるyamlファイルを直接は見ていません。翻訳ファイルを更新した場合、このindex.jsも更新する必要があります。更新する際は、

bin/console cache:warmup

を実行すれば、更新されます。

まとめ

今回はUxTranslatorでした。一度jsになるものの、同じ翻訳ファイルを使ってJS側も翻訳が可能になるのは楽ですね!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0