Reputation: 9592
I've searched around and I couldn't find one that really works.
In Mustache, when you throw 2 curly, the string inside will be escaped, and if you throw 3, it will NOT.
// when you pass {foo: '"bar"'} as hash, the following template will be:
{{foo}} // => "bar"
{{{foo}}} // => "bar"
right? So I created the following.
http://jsfiddle.net/beatak/6s5PU/
and this shows interpolate and escape opposite, meaning 2 curly for unescaped 3 for escaped. When I flip between escape
and interpolate
in _.templateSettings
, it just doesn't work. WHY? Underscore template has precedence of those three (escape
, interpolate
and evaluate
)?
I know I'm ignoring evaluate
on jsfiddle now, if that works together that'll be fantastic, but for now, I want to make 2 and 3 curly works just fine…
Upvotes: 2
Views: 465
Reputation: 11461
The regex for escape is searched, then interpolate, then evaluate. That's why your escaped form {{ }}
is matching before your unescaped form {{{ }}}
. You can change the order yourself in the source for _.template
.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
Changing the order of the lines above will change the priority.
If you don't want to change the underscore priority, you can use a more complex escaping regular expression. It's tricky to do without negative look-behind, but I came up with:
/\{\{([^\{\}]+?)(?!\}\}\})\}\}/
which should mean: {{
, followed by one or more non-brace characters, that shall not be followed by triple brace (}}}
), followed by double brace }}
. It works on your fiddle and hopefully will work for you.
Upvotes: 2