把手模板没有按预期渲染

时间:2015-06-12 00:48:55

标签: backbone.js handlebars.js

这是在Backbone视图中呈现的代码:

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

模板如下所示:

<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>

唯一呈现给页面的是表头:

  

用户名真实姓名电子邮件

我无法弄清楚为什么没有其他东西出现? &#34;你好:&#34;出现但是&#39; hi&#39;也没有呈现。

1 个答案:

答案 0 :(得分:1)

您需要使用each帮助程序循环遍历数组。 #users不是内置助手。

<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>

您还需要使用此版本的渲染:

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

以便在数据中定义用户。

相关问题