Backbone.js turning off wrap by div in render

BazZy picture BazZy · Oct 25, 2011 · Viewed 17.9k times · Source

I have model Post and collection Posts. And want to make form with list of all post in <select id="multi" multiple="multiple">. So i have to make a PostView render inside my #multi with just this template:

<option value=""><%= title %></option>

But finally I get it wrapped with div. Is there any solution for not wrapping this template with <div>?

Answer

kreek picture kreek · Oct 25, 2011

If you don't define an el (or tagName) for the view (in the class or during instantiation) the view will be placed inside a div tag. http://documentcloud.github.com/backbone/#View-el

var PostView = Backbone.View.extend({
  tagName: 'option'
});

UPDATE

Starting v0.9.0, Backbone has view.setElement(element) to get this done.

var PostView = Backbone.View.extend({
    initialize: function() {
        var template = _.template('<option value=""><%= title %></option>');
        var html = template({title: 'post'});
        this.setElement(html);
    }
});