0

我在使用 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 辅助块?

4

1 回答 1

0

您可以使用.or :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/

于 2013-02-14T21:18:29.667 回答