Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore template Uncaught ReferenceError variable is not defined [duplicate]

I am trying to render a basic backbone view with an underscore template, but I keep getting the following error when attempting to render the template.

Uncaught ReferenceError: amount is not defined

here's the jsfiddle: http://jsfiddle.net/rkj6j36n/

HTML

<body>
    <div class="msg-con"></div>
</body>

JS

DumbViewObj = Backbone.View.extend({
    el: $('.msg-con'),
    initialize:function(){
        this.render();
    },
    render: function(){
        var template = _.template('I am <%= amount %> dumb',{amount:'200'});
        this.$el.append(template);
    },
});
var dumb = new DumbViewObj();

I'm sure the solution is something dead simple, but I can't figure it out

like image 332
Optemino Avatar asked Sep 26 '14 18:09

Optemino


3 Answers

Because template is a function and template( obj ) returns the string you are after, it does not return the string after you call it.

What your code is doing

var xxx = template();
this.$el.append(xxx);

what you should be doing

render: function(){
    var template = _.template($('#dumb').html());
    var vars = {amount:200};
    var html = template(vars);
    this.$el.append(html);
},
like image 143
epascarello Avatar answered Oct 18 '22 10:10

epascarello


in one line:

this.$el.append(_.template('I am <%= amount %> dumb')({amount:200}))
like image 33
aleha Avatar answered Oct 18 '22 11:10

aleha


_.template compiles the template into a function. You have to pass the parameters to the resulting function to be evaluated:

    var template = _.template('I am <%= amount %> dumb');
    this.$el.append(template({amount:'200'}));
like image 21
dreyescat Avatar answered Oct 18 '22 10:10

dreyescat