david419
david419

Reputation: 435

Underscore JS template throwing Reference Error variable undefined

var resultTemplate = "" +
"    <ul class='searchList'>" +
"        <% _.each(paymentActions,function(paymentActivity){ %>" +
"            <li><span class='amount visible-phone'>-<%= paymentActivity.grossAmount %></span>" +
"            </li>" +
"        <% }); %>" +
"    </ul>";


var template = _.template(resultTemplate,{paymentActions : jsonData});

Error I am getting is(on the last line of the code snippet):-

Uncaught ReferenceError: paymentActions is not defined(…)

If I manually put a json Value in the var resultTemplate line instead of paymentActions it works fine. So the below code is executing fine:-

var resultTemplate = "" +
"    <ul class='searchList'>" +
"        <% _.each([{grossAmount:100},{grossAmount:200}],function(paymentActivity){ %>" +
"            <li><span class='amount visible-phone'>-<%= paymentActivity.grossAmount %></span>" +
"            </li>" +
"        <% }); %>" +
"    </ul>";

Can anyone help to debug this?

Upvotes: 0

Views: 144

Answers (1)

mikeapr4
mikeapr4

Reputation: 2856

You may have upgraded Underscore recently, the signature of the _.template() function has changed since 1.7.0:

Underscore templates no longer accept an initial data object. _.template always returns a function now.

Here's a working version:

var jsonData = [{grossAmount:100},{grossAmount:200}];

var resultTemplate = "" +
"    <ul class='searchList'>" +
"        <% _.each(paymentActions,function(paymentActivity){ %>" +
"            <li><span class='amount visible-phone'>-<%= paymentActivity.grossAmount %></span>" +
"            </li>" +
"        <% }); %>" +
"    </ul>";

var template = _.template(resultTemplate)({paymentActions : jsonData});

console.log(template);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>

The difference being:

var template = _.template(resultTemplate)({paymentActions : jsonData});

Upvotes: 1

Related Questions