Search code examples
symfonytwigmustacheverbatim

Using twig translations inside Moustache inside Twig


I have a moustache template inside my twig template. I use the moustache template in javascript and it contains some text and JS variables.

{# _partial.html.twig #}
{% verbatim %}
    <script id="insuranceOptionTpl" type="text/template">
        {{ #. }}
            <strong>My template is {{ adjective }}</strong>
        {{ /. }}
    </script>
{% endverbatim %}

Now I need to internationalize this page but my twig translations won't work inside verbatim. Is there any elegant ways to do that? I will probably have many different texts to translate, so ending and starting a new verbatim block all the time is not ideal.


Solution

  • By removing the verbatim block and by customizing Twig delimiters to be differents than Mustache ones, replacing {{ and }} by [[ and ]] for example (as explained in Twig doc), you'll be able to use Twig and Mustache in the same template:

    $twig = new Twig_Environment();
    
    $lexer = new Twig_Lexer($twig, array(
        'tag_comment'   => array('{#', '#}'),
        'tag_block'     => array('{%', '%}'),
        'tag_variable'  => array('[[', ']]'),
        'interpolation' => array('#{', '}'),
    ));
    $twig->setLexer($lexer);
    

    As most of your templates are already in Twig, you can change Mustache delimiters instead:

    $(document).ready(function () {
        var output = $("#output");    
        var template = $("#insuranceOptionTpl").html();
    
        //Custom tags for Mustache
        var customTags = [ '[[', ']]' ];
        Mustache.tags = customTags;
    
        // render string
        var data1 = "Hello world!";
        var html = Mustache.render(template, data1);
        output.append(html);
    });