1

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?

Ariel M
  • 175
  • 2
  • 10
  • i already check similar question like this http://stackoverflow.com/questions/4778881/how-to-use-underscore-js-as-a-template-engine?rq=1 – Ariel M Jun 06 '15 at 10:23

1 Answers1

1

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>
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144