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><%- value %></b>");
template({value : '<script>'});
=> "<b><script></b>"
Thanks in advance.
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
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.
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.
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.
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'}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With