Underscore.js template rendering

26,673

Solution 1

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.

Solution 2

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'}));
Share:
26,673
fadzril
Author by

fadzril

Updated on September 27, 2020

Comments

  • fadzril
    fadzril over 3 years

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

    var template = $(this.el).html(_.template(this.template, {'data': '&lt;script&gt;'}));
    $(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.