Handlebars template not rendering as expected

614 Views Asked by At

Here's the code that renders inside a Backbone view:

   var template = Handlebars.compile($('#some-hbs-template').html());
   var rendered = template({'hi':'sir','users':[{'username:':'denman','firstName': 'alex', 'lastName': 'mills'}]});
   this.$el.html(rendered);

the template looks like so:

<script id="some-hbs-template" type="text/x-handlebars-template">
    hello:{{hi}}
    <table>
        <thead>
        <th>Username</th>
        <th>Real Name</th>
        <th>Email</th>
        </thead>
        <tbody>
        {{#users}}
            <tr>
                <td>{{username}}</td>
                <td>{{firstName}} {{lastName}}</td>
                <td>{{email}}</td>
            </tr>
        {{/users}}
        </tbody>
    </table>
</script>

the only thing that gets rendered to the page is the table headers:

Username Real Name Email

I can't figure out why nothing else is showing up? "hello:" shows up but 'hi' is not rendering either.

1

There are 1 best solutions below

4
On

You need to use the each helper to loop over an array. #users isn't a built-in helper.

<script id="some-hbs-template" type="text/x-handlebars-template">
    <table>
        <thead>
        <th>Username</th>
        <th>Real Name</th>
        <th>Email</th>
        </thead>
        <tbody>
        {{#each users}} // NOTICE THIS...
            <tr>
                <td>{{username}}</td>
                <td>{{firstName}} {{lastName}}</td>
                <td>{{email}}</td>
            </tr>
        {{/each}} //...AND THIS.
        </tbody>
    </table>
</script>

You will also need to use this version of your render:

var rendered = template({'users':[{'username':'denman','firstName': 'alex', 'lastName': 'mills'}]});

so that users is defined in the data.