Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js template rendering

I have this sample code to render simple unescapedHTML using underscore templating.

var template = $(this.el).html(_.template(this.template, {'data': '<script>'}));
$(this.parent).append(template);

But when it try to render it, it caused an error:

Uncaught TypeError: Object [object Object] has no method 'replace'

Can anyone please enlighten me what's the cause and how to solve it? Since in underscore documentation:

var template = _.template("<b>&lt;%- value %></b>");
template({value : '&lt;script&gt;'});
=> "<b>&lt;script&gt;</b>"

Thanks in advance.

like image 522
fadzril Avatar asked Nov 19 '11 18:11

fadzril


People also ask

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

What is underscore template?

The _. template() function is an inbuilt function in the Underscore. js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering.

What does underscore mean in JavaScript?

Underscore. js provides different types of functions and that function is helpful to programmers to build any type of application without the help of built-in objects. Basically, Underscore is the identifier in JavaScript that means we can identify or we can perform any kind of operation with the help of Underscore.


2 Answers

From the fine manual:

template _.template(templateString, [context])

Compiles JavaScript templates into functions that can be evaluated for rendering.

The first argument for _.template is supposed to be a string, not a jQuery object. Part of the internal processing for _.template calls the String#replace function and that's where your error comes from. You might want to use this instead:

var template = $(this.el).html(_.template(this.template.html(), {'data': '<script>'}));
$(this.parent).append(template);

Demo: http://jsfiddle.net/ambiguous/wPu6G/

The example you give works just fine:

http://jsfiddle.net/ambiguous/w2qWe/

So I don't know where the 'value' is not defined error you mention in your comment could be coming from.

like image 169
mu is too short Avatar answered Oct 02 '22 13:10

mu is too short


I just hit the same error while running node on the server. If you read the template file from disk and you don't specify the encoding then node.js will return a buffer. The error is basically the same because Underscore expects a string. Make sure that you specify an encoding so that you are passing a string to Underscore.

this will produce the error.

var template = _.template(fs.readFileSync('mytemplate.tpl'));

and this is good.

var template = _.template(fs.readFileSync('mytemplate.tpl', { 'encoding':'utf8'}));
like image 20
Michael Connor Avatar answered Oct 02 '22 13:10

Michael Connor