7

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

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Optemino
  • 73
  • 1
  • 1
  • 5

3 Answers3

18

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);
},
epascarello
  • 204,599
  • 20
  • 195
  • 236
5

in one line:

this.$el.append(_.template('I am <%= amount %> dumb')({amount:200}))
aleha_84
  • 8,309
  • 2
  • 38
  • 46
4

_.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'}));
dreyescat
  • 13,558
  • 5
  • 50
  • 38
  • @aktiv-coder Sorry I have not enough reputation points for comments. Your snippet is working because you are using an older version of underscore. Try to use 1.7 instead. – dreyescat Sep 26 '14 at 18:44