mustache.js:具有外部变量的可枚举对象

时间:2018-01-06 19:34:29

标签: javascript mustache

Iv'e通过this精彩教程。

var data = {
    employees: [
    {   firstName: "Christophe",
        lastName: "Coenraets"},
    {   firstName: "John",
        lastName: "Smith"}
    ]}; 
var template = "Employees:<ul>{{#employees}}" +
                            "<li>{{firstName}} {{lastName}}</li>" +
                            "{{/employees}}</ul>"; 
var html = Mustache.to_html(template, data); 
$('#sampleArea').html(html);

我的问题是如何迭代属于employees对象内部数据对象的某些属性?

以下是一个示例,我想在label标记结束前打印employees的每一个旁边的</li>

var data = {
    employees: 
    [{
        firstName: "Christophe",
        lastName: "Coenraets"
    }],
    label: "red"
};

var template = "Employees:<ul>{{#employees}}" +
                            "<li>{{firstName}} {{lastName}}" + 
                            "the label is: {{label}}" +
                            "</li>" +
                            "{{/employees}}</ul>"; 

但上述示例显然不起作用,因为labeldata的属性,而不是employees的属性。

1 个答案:

答案 0 :(得分:2)

你可以试试这个:用“../”更高一级

var template = "Employees:<ul>{{#employees}}" +
                            "<li>{{firstName}} {{lastName}}" + 
                            "the label is: {{../label}}" +
                            "</li>" +
                            "{{/employees}}</ul>"; 

另一个解决方案是渲染整个节点:

var template = "{{#data}}Employees:<ul>{{#data.employees}}" +
                                "<li>{{data.employees.firstName}} {{data.employees.lastName}}" + 
                                "the label is: {{data.label}}" +
                                "</li>" +
                                "{{/data.employees}}</ul>{{/data}}"