0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Symfony TranslationコンポーネントでEnumを翻訳する

Posted at

Symfonyでは Translation コンポーネントが用意されており、文字列を簡単に翻訳して表示できます。

例:

{{ "apple" | trans }}
translations/sample.ja.yaml
apple: りんご

とても便利なのですが、Enumに対してはうまく動作しません。

enum Fruit: string
{
    case APPLE = 'apple';
}
## fruit = Fruite::APPLE
{{ fruit | trans }} # エラーになる

こまった。

TranslatableInterface

Translationコンポーネントには TranslatableInterface というインターフェイスが存在します。これを使うと、Enum上に翻訳処理を記載することができます。


use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

enum Fruit: string implements TranslatableInterface
{
    case APPLE = 'apple';

    public function trans(TranslatorInterface $translator, ?string $locale = null): string
    {
        return $translator->trans($this->value, domain: 'sample', locale: $locale);
    }
}

TranslatableInterface::trans() メソッドを作り、その中で翻訳処理を行います。
TranslatorInterface::trans() メソッドを使い、domainに翻訳ファイル名を指定すれば、翻訳を行なってくれます。

## fruit = Fruite::APPLE
{{ fruit | trans }} # りんご

よかった

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?