'Passing Symfony Translation to Symfony Webpack Encore

With Symfony, I use translation, Twig and Webpack encore components.

I can translate in frontend Twig with :

'my_key'|trans

I use command yarn encore dev for generate my app.js, but PHP translation component it's not accessible in Javascript.

I have a lot of things to translate in javascript.



Solution 1:[1]

You have to use BazingaJsTranslationBundle which allows you to access translations you have exposed through javascript:

Translator.trans('key', {}, 'DOMAIN_NAME');

Translator.transChoice('key', 1, {}, 'DOMAIN_NAME');

Solution 2:[2]

  1. You could transform translations yaml to json with webpack or a task manager (gulp | grunt).
  2. Put built json translation files to assets.
  3. Require them inside js script.
  4. Emit locale value to frontend to choose proper translation json object inside js script.

Note: in webpack case you should run 2 steps consequently: first step will build translations to assets to be required in js scripts. second step will compile js scripts afterwards.

Here is a part of webpack encore config which transforms translations *.yaml files to json with 'js-yaml' and puts them into assets directory:

.addPlugin(new CopyWebpackPlugin(
    {
        patterns: [
            {
                from: './translations/*.yaml',
                to: './[name].json',
                transform(content) {
                    return Buffer.from(
                        JSON.stringify(
                            yaml.safeLoad(content.toString('utf8'), {schema: yaml.JSON_SCHEMA})
                        ),
                        'utf8'
                    )
                }
            }
        ],
    }));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 goto
Solution 2