【问题标题】:Handlebars not parsing data车把不解析数据
【发布时间】:2016-03-02 02:35:53
【问题描述】:

我正在尝试使用把手来解析 javascript 对象,但由于某种原因,把手没有正确加载数据......

这是我的模板文件:

{{> header}}
<h1>Handlebars JS Example</h1>
<script id="some-template" type="text/x-handlebars-template"> 
<table>
    <thead> 
        <th>Name</th> 
        <th>Job Title</th> 
        <th>Twitter</th> 
    </thead> 
    <tbody> 
        {{#users}} 
        <tr> 
            <td>{{fullName person}}</td> 
            <td>{{jobTitle}}</td> 
            <td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td> 
        </tr> 
        {{/users}} 
    </tbody> 
</table> 
</script>
    <body>
    <!-- Insertion point for handlebars template -->
        <div id="main" style="margin-left:100px">
        </div>
    </body> 
<script type="text/javascript" src="javascript/templating.js"></script> 

这是我的 .js 文件:

$(document).ready(function() {

    var source = $("#some-template").html(); 
    var template = Handlebars.compile(source); 

    var data = { 
        users: [ { 
            person: {
                firstName: "Garry", 
                lastName: "Finch"
            },
            jobTitle: "Front End Technical Lead",
            twitter: "gazraa" 
        }, {
            person: {
                firstName: "Garrasd", 
                lastName: "Finch"
            }, 
            jobTitle: "Photographer",
            twitter: "photobasics"
        }, {
            person: {
                firstName: "Garry", 
                lastName: "Finch"
            }, 
            jobTitle: "LEGO Geek",
            twitter: "minifigures"
        } ]
    }; 

    Handlebars.registerHelper('fullName', function(person) {
      return person.firstName + " " + person.lastName;
    });

    console.log(template(data));

    $("#main").append(template(data));

});

注意 - 当我使用 console.log(template(data)) 时,我得到以下信息:

<table>
<thead> 
    <th>Name</th> 
    <th>Job Title</th> 
    <th>Twitter</th> 
</thead> 
<tbody> 
</tbody> 

有人知道我做错了什么吗?我正在使用 node.js + express。

谢谢!!

【问题讨论】:

    标签: javascript express handlebars.js templating


    【解决方案1】:

    您没有为users 定义任何块助手,而是尝试在模板中使用它。

    更改这些行

    ...
    {{#users}} 
    ...
    {{/users}}
    ...
    

    对这些:

    ...
    {{#each users}}
    ...
    {{/each}}
    ...
    

    在此处查看文档:http://handlebarsjs.com/builtin_helpers.html#iteration

    每个块的帮助器

    您可以使用内置的 each 帮助器遍历列表。在 - 的里面 块,您可以使用它来引用被迭代的元素。

    【讨论】:

    猜你喜欢
    • 2015-05-18
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2017-05-20
    相关资源
    最近更新 更多