Skip to content Skip to sidebar Skip to footer

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: _.t

Solution 1:

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>"

Post a Comment for "Underscore Templating - Changing Token Markers"