开发者

how can I render this JSON use mustache.js without loop

here is the 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"
                }
            }
        ];

and my mustache template is:

        {{#event}}
        开发者_如何学JAVA    <div>
                <h2>{{name}}</h2>
                <span>on {{data}}</span>
                <p>{{address}}</p>
            </div>
        {{/event}

so the template code above don not work.What I do now is make a for loop :

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

Any better way to make it works without any loop?


here is one way to do the same with just mustaches templates. you set your data as follows:

 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"
        }
    }
]};

and your template should look as follows:

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

Hope that helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜