2

这是JSON:

   var data = [
            {
                "event": {
                    "name": "txt1",
                    "data": "2011-01-02",
                    "address": "Guangzhou Tianhe Mall"
                }
            },
            {
                "event": {
                    "name": "txt2",
                    "data": "2011-01-02",
                    "address": "Guangzhou Tianhe Mall"
                }
            },
            {
                "event": {
                    "name": "txt3",
                    "data": "2011-01-02",
                    "address": "Guangzhou Tianhe Mall"
                }
            }
        ];

我的胡子模板是:

        {{#event}}
            <div>
                <h2>{{name}}</h2>
                <span>on {{data}}</span>
                <p>{{address}}</p>
            </div>
        {{/event}

所以上面的模板代码不起作用。我现在要做的是for循环:

 var html = "";
 for(var i = 0; i < data.length; i++){
        html += Mustache.to_html(tmp, data[i]);
 }

有没有更好的方法让它在没有任何循环的情况下工作?

4

1 回答 1

4

这是仅使用 mustaches 模板执行相同操作的一种方法。您将数据设置如下:

 var data = {data: [
    {
        "event": {
            "name": "txt1",
            "data": "2011-01-02",
            "address": "Guangzhou Tianhe Mall"
        }
    },
    {
        "event": {
            "name": "txt2",
            "data": "2011-01-02",
            "address": "Guangzhou Tianhe Mall"
        }
    },
    {
        "event": {
            "name": "txt3",
            "data": "2011-01-02",
            "address": "Guangzhou Tianhe Mall"
        }
    }
]};

您的模板应如下所示:

{{data}}
{{#event}}
<div>
<h2>{{name}}</h2>
<span>on {{data}}</span>
<p>{{address}}</p>
</div>
{{/event}
{{/data}}

希望有帮助

于 2011-07-28T06:14:01.807 回答