3

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 %>
Golo Roden
  • 140,679
  • 96
  • 298
  • 425
  • precede with escape character???? – madhairsilence Jan 29 '13 at 07:34
  • And what *is* the escape character in this case? – Golo Roden Jan 29 '13 at 07:53
  • http://stackoverflow.com/questions/8298274/why-does-escape-modify-characters-in-underscore-js – madhairsilence Jan 29 '13 at 10:17
  • How do you feel about putting the `<%=...%>` in the value of `name` rather than the template? Is the final result going to be HTML? – mu is too short Jan 30 '13 at 02:29
  • Yes, the final result is going to be HTML. The point is that there *must* be any option to disable parsing. Otherwise it would not be possible to embed the string `<%= abc %>` as a string, without the need for another variable. – Golo Roden Jan 30 '13 at 06:04
  • @madhairsilence What exactly does the link you provided have in common with my question, except that it's both about escaping, but escaping in a completely different kind? – Golo Roden Jan 30 '13 at 06:05

2 Answers2

3

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' });
Evan Hahn
  • 12,147
  • 9
  • 41
  • 59
0

For a non-html specific solution, use unicode character escape sequences to escape <, > and %. Using your example, this:

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

Will output

foo ### <%= name %>
Sofia Paixão
  • 309
  • 2
  • 16