Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using <% in Underscore.js templating without parsing it

Usually, if you use templating by Underscore.js, any expression that looks like <% ... %> and <%= ... %> is parsed by Underscore.js

How do I escape such a value, in case I want to embed the text <% ... %> inside the template?

To put it in other words: How can I tell Underscore.js to ignore something that looks like a placeholder, but that isn't a placeholder?

I guess I have to use some kind of escaping, but the usual \ won't work. If I type

_.template('<%= name %> ### \<%= name %>', { name: 'foo' });

I get foo ### foo as a result, which is obviously not what I wanted.

Update: To make more clear, what I want from the line above - it should result in

foo ### <%= name %>
like image 599
Golo Roden Avatar asked Sep 08 '26 10:09

Golo Roden


1 Answers

If your final output is going to be HTML, you could replace < and > with their HTML escape code thingers:

_.template('<%= name %> ### &lt;%= name %&gt;', { name: 'foo' });

You could also modify Underscore's template settings to support these things, so that <%= ... %> means nothing to Underscore:

_.templateSettings = {
    interpolate: /\{\{(.+?)\}\}/g
};
var t = _.template('{{name}} ### <%= name %>', { name: 'foo' });
like image 56
Evan Hahn Avatar answered Sep 12 '26 18:09

Evan Hahn