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 %>
6
  • precede with escape character???? Commented Jan 29, 2013 at 7:34
  • And what is the escape character in this case? Commented Jan 29, 2013 at 7:53
  • stackoverflow.com/questions/8298274/… Commented Jan 29, 2013 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? Commented Jan 30, 2013 at 2: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. Commented Jan 30, 2013 at 6:04

2 Answers 2

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' });
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.