1

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.

ecc
  • 1,490
  • 1
  • 17
  • 42

1 Answers1

2

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);
});
Veve
  • 6,643
  • 5
  • 39
  • 58
  • Oh, of course! I was thinking of using JS translations but this is really not elegant. I have way too many twig templates and just a few mustache ones. Can I change just Mustache's delimiters? – ecc Dec 01 '16 at 21:02