Search code examples
javascriptunderscore.jsfrontendunderscore.js-templating

Underscore.js template compilation


Basically what I'm trying to do is to compile template with some data usin underscore js. My code follows:

var temp = "<div> Hello <%=names%> </div>";
var html = _.template(temp, {names:'world'};

I'm expecting for my variable html to be

<div> Hello world </div> 

but for some reason variable names is undefined while compilation and template never compiles.

This is the most basic thing with underscore js and according to documentation and numerous examples on web it should work. What am I doing wrong?


Solution

  • The _.template function has changed a little bit, assuming you're on the latest version, it now produces a function instead of the compiled HTML which you have to call with the data you want to be displayed.

    var temp = "<div> Hello <%= names %> </div>";
    var html = _.template(temp);
    console.log(html({names:'world'}));
    
    "<div> Hello world </div>"