nested template rendering in backbone.js


I have a template like

script type: "text/template", id: "list-template", '''    
    <div class="display">
        <div id="list-name"><%= name %></div>        
        <span class="list-destroy"></span>
        <ul id="ul-cards">

    <div class="edit">
          <input class="list-input" type="text" value="<%= name %>" />
          <input id="btnEdit" type="button" value="Save" class="primary wide js-add-list" />
          <input id="hdnListId" type="hidden" value="<%= listId%>" />
    <form class="add-list-card js-add-list-card clearfix"> 
        <textarea placeholder="Add card" class="new-card"></textarea> 
        <input type="button" value="Add" class="primary js-add-card"> 
        <a class="app-icon close-icon dark-hover cancel js-cancel-add-card" href="#" id="closeCard"></a> 

in this template i have <ul id="ul-cards"> element in which i want to render another template which display list inside this ul. this template is :

script type: "text/template", id: "card-template", '''    
        <span class="card-name"><%= name %></span>

is it possible or i have to do it in another way? please help me if anyone have idea. thanks in advace.

it is worked but still i have one problem in data display in <ul id="ul-cards"> there sholud be 2

  • as per records in my database but it will display only 1
  • . data fetch properly but display only last data.

    Problem courtesy of: priyanka patel
  • Solution

    There are two ways to do this: the DOM way and the template way.

    The DOM way involves adding your views using DOM methods: you have your ListView and your CardView; the ListView invokes individual CardViews that fill in the ListView's element.

    The template way requires that you remember this: backbone's views are policy frameworks, not policy templates. Render doesn't have to render into the DOM. You can use render() to return a string, for example. If your event manager is on the ListView object only (possible; I've done this), then you can have ListView invoke "the resulting array of an array of CardView renders" and insert that directly into ListView's template. This is actually faster, as you only require the browser to analyze the entire ListView HTML blob once, when it's inserted into the innerHTML of the parent DOM object.

    Solution courtesy of: Elf Sternberg


    There is currently no discussion for this recipe.

    This recipe can be found in it's original form on Stack Over Flow.