如果JSON对象在嵌套数组中,如何使用Mustache.js?

nol*_*bel 7 javascript jquery templates mustache

我听说过Mustache的精彩内容,并决定尝试一下.

我试图弄清楚如何使用jQuery的Mustache模板.我一直在寻找几天.

小胡子可以在这里找到:https://github.com/janl/mustache.js/

这是我的尝试:

$.getJSON('get_fullname.asp', {name: 'johnny'}, function(data, status, xhr) {

    var template = '<h1>{{NAME}}</h1><p>test</p>';
    strHTML = Mustache.to_html(template, data);
    $('#container').html( strHTML );

});
Run Code Online (Sandbox Code Playgroud)

我的JSON数据返回 [{"NAME":"John","MIDDLE":"A","LAST":"Smith"}]

我得到的只是<p>test</p>.

我也尝试过使用这个模板,但仍然可以使用<p>test</p>.

var template = '{{#NAME}}<h1>.</h1>{{/NAME}}<p>test</p>';
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

Gaz*_*ler 8

一目了然,您的JSON对象似乎嵌套在一个数组中.删除它周围的[]然后查看它是否有效.你可以在服务器级别(我推荐)或在javascript中通过调用:

strHTML = Mustache.to_html(template, data[0]);
Run Code Online (Sandbox Code Playgroud)

代替:

strHTML = Mustache.to_html(template, data);
Run Code Online (Sandbox Code Playgroud)