user1412777
user1412777

Reputation: 67

Render Sub View Within View in Backbone

Hi I am struggling to understand how I would do the following.

I have a backbone view that I render, I would then like to add another view to a dom element within that view.

Here is my code as it stands:

define([
  'jquery',
  'underscore',
  'backbone',
  'views/common/parent',
  'text!templates/currentAccounts.html',
  'text!templates/guidesTools.html'
], function($, _, Backbone, ParentView, mainTemplate, subTemplate){

var accountsView = ParentView.extend({
    render : function() {
        this.$el.html(mainTemplate);
    }
});

return new accountsView;

});

I now need to attach the subtemplate (guidesTolls.html) to a dom element within the main template. What would be the best way to do this ?

Upvotes: 0

Views: 637

Answers (1)

Zhongjie Wu
Zhongjie Wu

Reputation: 317

Please try to learn the example from http://backbonejs.org/#examples-todos

In this part there are two models and three views

  • Models/Collection
    • Todo Model
    • TodoList Collection
  • Views
    • Todo View
    • TodoList View
    • App View

The App View render a view based on the TodoList View, which renders Todo View of each Todo object.

Your case is simpler than that. Specifically, you can do something like this to have a view with subviews

<div id="main">
</div>
<script type="text/template" id="main-template">
    <h3>main view</h3>
    <ul>
      <li><%= account.id %></li>
      <li><%= account.name %></li>
    <ul>
    <div id="guide-tools"></div>
</script>

Javascript:

var accountsView = ParentView.extend({
    el: $("#main")
    render : function() {
        var template = _.template($("#main-template").html());
        var guideTemplate = "Guide Tool Text";
        this.$el.html(template(this.model.toJSON()));
        this.$("#guide-tools").html(guideTemplate);  // will insert the guide page to the #main div
    }
})

Note: I don't know how to get the text from the html file, especially if you are using server side scripts.

Upvotes: 1

Related Questions