Gimali
Gimali

Reputation: 787

handlerbar template with backbone inside div does not render

Example fiddle set up here

I've following template that renders successfully with handlerbarjs -

<ul>
    {{#each models}}<li>{{attributes.subject_name}}</li>{{/each}}
</ul>

But with having same data passing to different template it does not render. If I try to replace li with table, it's not working.

<table class="table">
    <thead>
        <tr>
            <th>Name</th>               
        </tr>
    </thead>        
    {{#each models}}
         <tr>
            <td>{{attributes.subject_name}}</td>            
        </tr>
   {{/each}}
</table>

Code that compiles tempalte -

 template: Handlebars.compile($("#subjectList").html()) ,

#subjectList is ID of parent div ( not mentioned in question )

And this is how I pass data to tempalte -

this.$el.html(this.template(this.collection));

As I inspected in DevTools I can see collection is being loaded correctly and as first template is getting rendered I think data is being passed correctly.

Upvotes: 0

Views: 147

Answers (1)

mu is too short
mu is too short

Reputation: 434585

The template in your jsfiddle example:

{{#each subjects}}
    <li>{{subject_name}}</li>
{{/each}}

<table class="table">
    {{#each subjects}}
        <tr>
            <td>{{subject_name}}</td>
        </tr>
    {{else}}
        <tr>
            <td colspan="4">No Subjects Added Yet.</td>
        </tr>
    {{/each}}
</table>

is not valid HTML. If you put that inside a <div> (even a hidden one), the browser will often try to rewrite it to make it valid HTML. That clean up process generally butchers your template.

You need to put your template inside something that the browser won't try to interpret. The standard solution is to use a <script> with an appropriate content type:

<script id="subjectlist" type="text/x-handlebars">
    ...
</script>

Also, an <li> needs to have a <ul>, <ol>, or <menu> parent so your jsfiddle template should look more like this:

<script id="subjectList" type="text/x-handlebars">
    <ul>
        {{#each subjects}}
            <li>{{subject_name}}</li>
        {{/each}}
    </ul>
    ...
</script>

Demo: http://jsfiddle.net/ambiguous/kxc52/

Upvotes: 3

Related Questions