Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore templating - changing token markers

Out of the box underscore templating uses the markers <%= %> for raw, and <%- %> for HTML escaped content.

I know you can change the markers using something like:

_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;

But how does this relate to raw and escaped content? It looks to me like you end up with only one type of marker. Or have I overlooked something?

like image 687
UpTheCreek Avatar asked Mar 21 '12 10:03

UpTheCreek


1 Answers

The Underscore.js documentation says this (emphasis added):

If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string.

So you can just give the _.templateSettings object an escape property:

_.templateSettings.escape = /\{\{-(.*?)\}\}/g
>>> compiled = _.template("Escaped: {{- value }}\nNot escaped: {{ value }}")
>>> compiled({value: 'Hello, <b>world!</b>'})
"Escaped: Hello, &lt;b&gt;world!&lt;&#x2F;b&gt;
Not escaped: Hello, <b>world!</b>"
like image 51
Felix Loether Avatar answered Sep 28 '22 04:09

Felix Loether