Tag Archives: underscoreJs

Change Underscore.js template settings

== template ==
_.template(templateString, [data], [settings])

http://underscorejs.org/#template

: Template functions can both interpolate variables, using <%= … %>, as well as execute arbitrary JavaScript code, with <% … %>. If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %>

var compiled = _.template("hello: <%= name %>");
compiled({name : 'moe'});
=> "hello: moe"

var list = "<% _.each(people, function(name) { %> <li><%= name %></li> <% }); %>";
_.template(list, {people : ['moe', 'curly', 'larry']});
=> "<li>moe</li><li>curly</li><li>larry</li>"

var template = _.template("<b><%- value %></b>");
template({value : '<script>'});
=> "<b><script></b>"

You can also use print from within JavaScript code. This is sometimes more convenient than using <%= ... %>.

var compiled = _.template("<% print('Hello ' + epithet); %>");
compiled({epithet: "stooge"});
=> "Hello stooge."

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.

== Underscore.js Template Settings =

// Underscore.js Template Settings
_.templateSettings = {
    interpolate: /\{\{\=(.+?)\}\}/g,
    escape: /\{\{\-(.+?)\}\}/g,
    evaluate: /\{\{(.+?)\}\}/g
};
var compiled = _.template("hello: {{= name }}");
compiled({name : 'moe'});
=> "hello: moe"

var list = "{{ _.each(people, function(name) { }} <li>{{= name }}</li> {{ }); }}";
_.template(list, {people : ['moe', 'curly', 'larry']});
=> "<li>moe</li><li>curly</li><li>larry</li>"

var template = _.template("<b>{{- value }}</b>");
template({value : '<script>'});
=> "<b>&lt;script&gt;</b>"