Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use multiple translation files without domains in Twig in Symfony2?

In the Symfony2 project, I'm working on, the translations are files in multiple domain files like

foo.en_GB.xlf
bar.en_GB.xlf
buz.en_GB.xlf
...
foo.de_DE.xlf
bar.de_DE.xlf
buz.de_DE.xlf
...
foo.fr_FR.xlf
...

So in the Twig files I have to define the domain, e.g.:

{% trans from 'my_domain' %}my_key{% endtrans %}

Actually I don't need the domains in this project. All the translations are part of one big domain. So, I want (1) to use multiple translation files and (2) in the same time not to care about the domain, so that

{% trans %}my_key{% endtrans %}

should work for the my_key translated in any /.../translations/*.xlf file.

How to use multiple translation files without domains in a Twig template in Symfony2?

like image 400
automatix Avatar asked Oct 28 '25 23:10

automatix


1 Answers

This can be achieved by creating a custom loader without break nothing, all you need is to use a different file extension:

namespace AppBundle\Translation\Loader;

use Symfony\Component\Translation\Loader\XliffFileLoader;

class FooFileLoader extends XliffFileLoader
{
    /**
     * {@inheritdoc}
     */
    public function load($resource, $locale, $domain = 'messages')
    {
        // ignoring $domain var and pass 'messages' instead
        return parent::load($resource, $locale, 'messages');
    }
}

Register the translation loader:

services:
    app.translation.loader.foo:
        class: AppBundle\Translation\Loader\FooFileLoader 
        tags:
            - { name: 'translation.loader', alias: 'foo' }

Later, you must name all your files to:

bar.en_GB.foo
baz.en_GB.foo
bar.de_DE.foo
baz.de_DE.foo
...

All your translation files with .foo extension will be merged and included into messages domain.

like image 65
yceruto Avatar answered Nov 01 '25 11:11

yceruto