user1336103
user1336103

Reputation: 3887

_.template not working - backbone.js

Trying to output some value from View via template by using Backbone.js, but the list item is not showing on webpage, please have a look and advise what is missing. Thank you

<script type="text/template" id="myid">
    <li>  <%= value %> </li>
</script>
<script type="text/javascript">
(function($){
    ListView = Backbone.View.extend({
        tagName:'ul',
        initialize:function(){
            this.template = _.template($('#myid').html());
        },
        render:function(){
        this.$el.append(this.template({value:"Joe Blogg"}));
        return this;    
        }
    });
    $(document).ready(function(e) {
        myListView = new ListView();
    });
  })(jQuery);

Upvotes: 1

Views: 4303

Answers (3)

GeckoTang
GeckoTang

Reputation: 2795

Please try this.

(function($){
    var ListView = Backbone.View.extend({
        tagName:'ul',
        $el: $(this.tagName),
        initialize:function(){
            this.template = _.template($('#myid').html());
        },
        render:function(){
            this.$el.append(this.template({value:"Joe Blogg"}));
            $('body').append(this.$el);
        }
    });
    $(document).ready(function(e) {
        var myListView = new ListView(); // call initialize()
        myListView.render(); // call render()
    });
})(jQuery);

I use jQuery.js and Underscore.js and Backbone.js.

And Always Use "var".

Upvotes: 4

Sushanth --
Sushanth --

Reputation: 55750

Try this

   this.$el.empty();
   this.$el.html(this.template(this.model.attributes));

In your DOM ready event call the .render() method

$(document).ready(function(e) {
     myListView = new ListView();
     myListView.render(); 
 });

Upvotes: 1

ericponto
ericponto

Reputation: 736

You need to call render and then actually add your view's el to the page somewhere.

$(document).ready(function(e) {
   var myListView = new ListView();
   $("body").append(myListView.render().el); 
 });

Upvotes: 0

Related Questions