Search code examples
javascriptbackbone.jsunderscore.jsunderscore.js-templating

Underscore template Uncaught ReferenceError variable is not defined


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


Solution

  • 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);
    },