Escape double braces {{ ... }} in Mustache template. (templating a template in NodeJS)
Solution 1
You can switch delimiters to something that won't conflict with the triple mustaches, like erb-style tags:
{{=<% %>=}}
{{{
{
"name": "<% name %>",
"description": "<% description %>"
}
}}}
{{{debug this}}}
<%={{ }}=%>
Note that you can do this as many times as you like throughout your template. Any time you run into something that conflicts, pick a new set of delimiters :)
Solution 2
As described in this Question handlebars doesn't support changing the delimiters. But you can escape the double braces with a backslash like this:
HTML:
... \{{ myHandlbarsVar }} ...
Solution 3
You can also assign Mustache.tags = ["[[", "]]"];
before your template compilation.
http://jsfiddle.net/fhwe4o8k/1/
e.g.
$(function () {
Mustache.tags = ["[[", "]]"];
var template = $('#test').html();
Mustache.parse(template);
var rendered = Mustache.render(template, {test: "Chris"});
$('#content-placeholder').html(rendered);
});
Solution 4
another option is create a helper for outputing curly brackets.
Handlebars.registerHelper('curly', function(object, open) {
return open ? '{' : '}';
});
and then use it in the template like this:
<script id="template" type="text/x-handlebars-template">
{{curly true}}{{name}}{{curly}}
</script>
which then outputs:
{Stack Over Flow Rocks}
Comments
-
Nick Jonas over 2 years
I'm trying to template a template, like below:
{{{ { "name" : "{{name}}", "description" : "{{description}}" } }}} {{{debug this}}}
<h1>{{name}}</h1>
Where I want to triple brackets to stay, but double brackets to be replaced with the JSON passed in. Anyone know the best way to do this without writing post-process JS code, and if not, is there a good nodeJS template engine for this type of scenario?
-
Gwendal Roué over 11 yearsIn Handlebars you escape braces with a backslash.
-
bobthecow over 11 yearsWait. You were wondering about Handlebars? You tagged it as Mustache and Mustache.js, and didn't even mention Handlebars :)
-
Arnaud Meuret almost 10 yearsYou've got to be kidding. You accept your own answer that does not answer your own question which is perfectly addressed by @bobthecow?
-
tandrewnichols over 8 yearsThis doesn't work in Mustache . . . and this question is specifically about mustache. Clearly, people have found this answer useful, so no downvote from me, but wanted to comment for anyone who found this and thought it might solve all their problems.
-
Guido Tarsia over 7 yearsworked for me in handlebars, I can even do stuff like
\{{ unrendered {{ data }} }}
-
Nevitones over 3 years2021 and this answer is still saving people(like me), thanks a lot! Handlebars documentation link: handlebarsjs.com/guide/…