How to add a new domain for translations in Symfon

2019-08-07 04:59发布

问题:

I'm using symfony and in my bundle I need to create some translations, but I rather do it in a different domain than "messages", like FOS User Bundle does (they use the FOSUserBundle domain).

So I created a MyBundle.en.yml file with my translations, but they are not loaded. I've read in the documentation I need to do this:

$translator->addLoader('xlf', new XliffFileLoader());

$translator->addResource('xlf', 'messages.fr.xlf', 'fr_FR');
$translator->addResource('xlf', 'admin.fr.xlf', 'fr_FR', 'admin');
$translator->addResource(
    'xlf',
    'navigation.fr.xlf',
    'fr_FR',
    'navigation'
);

http://symfony.com/doc/current/components/translation.html#using-message-domains

But where should I do that?

Update

After some investigation, if I run the debug for the translations it says that all the translation I'm using for my domain in the template are missing.

My translation file is located at src/Acme/Bundle/MyBundle/resources/translations/MyDomain.yml

I tried to located in app/Resources/translation/MyDomain.yml but same result.

I also tried to delete the cache (rm -rf app/cache) but still not working

回答1:

Symfony will automatically do this for you if you place your files in the correct location(s). You can find a full description of the conventions assumed by Symfony in the documentation: https://symfony.com/doc/current/translation.html#translation-resource-file-names-and-locations

The Best Practices-guide recommends storing them in app/Resources/translations/. Alternatively you can put them in your bundle's translations folder: src/MyBundle/Resources/translations.

Please be aware that you have to specify your domain when using the translator, e.g. in your twig templates. See:

  • https://symfony.com/doc/current/components/translation.html#using-message-domains
  • https://symfony.com/doc/current/translation.html#twig-templates


回答2:

you have to specify the domain name. for example in twig:

{{ some_things | trans({}, 'my_domaine_name') }}