Ariel M
Ariel M

Reputation: 205

underscore.js template function referenceError

I'm trying to use underscore.js template function on the following code based on http://underscorejs.org/#template and other tutorials

json = {"data": [{"img0": "image.jpg"}]}
var compiled = _.template("image: <%= img0 %>");
compiled(json.data[0]);
document.getElementById("albums").innerHTML = compiled();

but i got this error:

Uncaught ReferenceError: img0 is not defined

Can you explain to me what the problem is?

Upvotes: 1

Views: 279

Answers (1)

Oleksandr T.
Oleksandr T.

Reputation: 77482

You need pass arguments to template function when you call it,

var json = {"data": [{"img0": "image.jpg"}]};
var compiled = _.template("image: <%= img0 %>");

document.getElementById("albums").innerHTML = compiled(json.data[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<div id="albums"></div>

Upvotes: 1

Related Questions