Search code examples
javascriptjquerytemplatesbackbone.jsunderscore.js

backbone template nested in another template


Is it possible to have a template nested inside a template and access via backbone view?

For example I have View1 using Template1, and View2 using Template2. Template2 actually needs to be in a DIV inside of Template1. I put the DIV container for template2 inside template1 with the appropriate id, but it doesn't show when page is rendered. If I remove Template2 div container from inside Template1 and just put it in the page body it works fine.

So just wondering if this is possible, or if I have to nest the views/models, etc. to make this work?

The data in Template2 is not technically related to Template1 is just needs to display in a position on the page that's embedded in Template1.


Solution

  • The way I've dealt with this in the past is to define both views separately, and then when you render View1, create a new View2, render it, and insert it into View1. So:

    window.View1 = Backbone.View.extend({
        render: function() {
            this.view2 = new View2();
            this.$('insert-view-here').append(this.view2.render().el);
        }
    });