supershnee
supershnee

Reputation: 1276

What does interpolate mean in the context of underscore.js's template function?

I'm trying to understand the difference between underscore's template method's markup types.

Specifically, I'm trying to figure out the difference between underscores <%- %> markup and <%= %> aside from HTML-escaping. Are there any other differences between the two types?

From underscore's documentation:

If you wish to interpolate a value, and have it be HTML-escaped, use <%- … %>

What does interpolate mean in this context?

Upvotes: 3

Views: 2108

Answers (3)

Sushanth --
Sushanth --

Reputation: 55750

It means evaluate and populate..

Lets say you have

Lets say after you convert the model attributes to JSON this is the object

{
   title : 'Hello World',
   escapeTitle : '<Hello World >'    
}; 

If you do this

<%= {{title}} %>         // Displayed as -- Hello World 
<%= {{escapedTitle}} %>  // Displayed as -- &#60;Hello World&#62;

But if you use this

<%- {{escapedTitle}} %>  // Displayed as -- <Hello World>

So first it is evaluated if there are any characters if the user wants to be escaped and then populates it

Upvotes: 4

Peter Lyons
Peter Lyons

Reputation: 146164

interpolate means to evaluate a javascript expression and place the resulting value within the template data. For example:

_.template('Hello, <%- name %>', {name: 'Tony'})

will return Hello, Tony. That's interpolation, as opposed to evaluation, which is where you can you expressions for control flow or other expressions whose purpose is not just to compute a value that will become part of the template output string.

Upvotes: 0

Rayweb_on
Rayweb_on

Reputation: 3727

Underscore will change the value of the parameter inside your <% %> declaration for example <%-firstName %> for the value of the property firstname of the JSON you pass to the template. it means is replacing the variable declaration for the actual value. the diference of the - = is just that if you want this value to be HTML scaped.

Upvotes: 2

Related Questions