【问题标题】:The each block helper每个块助手
【发布时间】:2013-01-30 18:53:53
【问题描述】:

我在使用 Handlerbars.js 的 each 块助手时遇到了麻烦

<html>
<head>
    <script>
    </script>

    <script id="entry-template" type="text/x-handlebars-template">
        <div class="entry">
            {{#each people}}
                <p>{{firstName}} &nbsp;{{lastName}}</p>
            {{/each}}
        </div>
    </script>


    <script src="lib/jquery-1.8.2.min.js"></script>
    <script src="lib/handlebars.js"></script>

    <script type='text/javascript'>
        $(document).ready(function(){
          var people = [
            {firstName: "Yehuda", lastName: "Katz"},
            {firstName: "Carl", lastName: "Lerche"},
            {firstName: "Alan", lastName: "Johnson"}
          ] 

          var source   = $("#entry-template").html();
            var template = Handlebars.compile(source);
            var html = template(people);
            $('#content').html(html);
        });
    </script>
</head>
<body>
    <div id="content">
    </div>

</body>
</html>

如果我将模板更改为下面的代码,一切顺利:

<script id="entry-template" type="text/x-handlebars-template">
    <div class="entry">
        {{#.}}
            <p>{{firstName}} &nbsp;{{lastName}}</p>
        {{/.}}
    </div>
</script>

如何使用 each 辅助块?

【问题讨论】:

    标签: javascript javascript-framework handlebars.js


    【解决方案1】:

    您可以将.this{{#each}} 一起使用:

    <script id="entry-template" type="text/x-handlebars-template">
        <div class="entry">
            {{#each .}}
                <p>{{firstName}} &nbsp;{{lastName}}</p>
            {{/each}}
        </div>
    </script>
    

    或:

    <script id="entry-template" type="text/x-handlebars-template">
        <div class="entry">
            {{#each this}}
                <p>{{firstName}} &nbsp;{{lastName}}</p>
            {{/each}}
        </div>
    </script>
    

    演示:

    {{#each people}} 的问题在于模板不知道您为 JavaScript 对象使用的名称。如果您想使用{{#each people}},则必须添加另一层:

    var html = template({ people: people });
    

    演示:http://jsfiddle.net/ambiguous/3tKET/

    【讨论】:

    • 您也可以使用{{#each this}},这可能更容易阅读:]
    • @Ben:很好,我已经添加了这个替代方案以确保完整性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-08
    相关资源
    最近更新 更多