Search code examples
symfonytwig

What is the best way to translate JavaScript literal strings in Assetic assets?


I'm using Symfony2 to develop a application that is to be translatable. The application has Assetic enabled to minify and combine *.js and *.css files. However, I have a jQuery plugin I wrote, that has literal strings in it. For example, consider the following code:

       $('<p>Are you sure you want to proceed?</p>').dialog({
            buttons: {
                "Yes" : function() {
                    // ...
                },
                "No" : function() {
                    // ...
                }
            }
        });

In the above snippet, "Are you sure...", "Yes" and "No" will always be English, and I can't use Twig templating in the .js file to translate it using something like: {{ "yes"|trans }}

What I want to know is, what would be the best way to use Twig to leverage the built in Symfony2 translation mechanism, to translate the literal strings in my JS scripts.

Is there a way to create for example: myscript.js.twig files?


Solution

  • Is there a way to create for example: myscript.js.twig files?

    It seems a bad idea.


    You can check https://github.com/willdurand/BazingaExposeTranslationBundle

    or create it yourself, for example include this in your template:

    <script type="text/javascript">
        var translations = {
           // ... 
           'yes' : {{ 'yes' | trans }},
           // ...
        }
    </script>
    

    then if your javascript file is included just before </body> you can use translations variable in it.