variables inside underscore.js template

javascript, template-engine, underscore.js

Solution

Your try 2 is almost right but the tag where you output encodedTitle is missing the `=` at the start and doesn't need the `+` in the string. Should be:

<p><%= encodedTitle %></p>

Alternatively you could also do:

<p><% print(encodedTitle) %></p>

In underscore templates, any javascript you want evaluated must be contained inside `<% %>`, hence why your second attempt just outputs the the javascript as a string. You correctly used the `=` in your sample at the top but omitted it in try 2.

The `=` tells the templating engine to output the result of the enclosed javascript as a string. If you don't use the `=`, the javascript is executed, but nothing is output. Underscore's templates provide the `print()` function as an alternative to using the `=`, I dont know that one way is better than the other.

Problem

How to set up variables inside an `underscore.js` template for an app built with `backbone.js`? I just want to create reusable processed strings. Also, can `underscore.js`'s built-in functions like `_.escape` be used to process those variables? ``` <script type="text/html" id="templateresults"> <p><%= encodeURIComponent(title) %></p> // this works // try 1: var encodedTitle = encodeURIComponent(title); // shows up as regular text <p>'+encodedTitle+'</p> // this doesn't work and shows up as regular text // try 2: <% var encodedTitle = encodeURIComponent(title); %> // nothing shows up <p><% '+encodedTitle+' %></p> // nothing shows up </script> ``` `title` is a JSON item (text string). Encoded output: `This%20is%20a%20Sample%20Title` Regular output: `This is a Sample Title`

Original source