如何使用没有根节点的JSON呈现Mustache模板

Jes*_*sik 2 jquery json jsonp mustache

我正在构建一个小页面,使用jquery的getJSON调用API,然后使用胡子模板(至少是计划)呈现数据.但是我的JSON没有节点根,并且无法使用正确的胡子机制循环访问JSON响应数据.

//start
file : jsonresponse.jsonp

?([{"CountryIsoAlpha3Code":"AFG","CountryName":"Afghanistan"},
{"CountryIsoAlpha3Code":"ALA","CountryName":"Åland Islands"},
{"CountryIsoAlpha3Code":"ALB","CountryName":"Albania"}])
//end

//start
file: tmpl.mustache

<option value="{{CountryIsoAlpha3Code}}">{{CountryName}}</option>
//end

//start
file: render.js

$.getJSON(jsonresponse.jsonp, function(data) { 
   var tpl = tmpl.mustache,
   i=data.length,
   html = '';
     while(i--){
       html = html + mustache.render(tpl, data[i]);
     }

//end
Run Code Online (Sandbox Code Playgroud)

我意识到这是完全错误的(仅在模板使用中,假设我实际上正在传递数据和模板)但它确实有效.但如果我想做以下怎么办...我该怎么做!?:

//start
//file : daydreamer.mustache

<h1>This title is only awesome when it's rendered once</h1>
{{#}}  //no root node attempt at recursive templating rendering
     <option value="{{CountryIsoAlpha3Code}}">{{CountryName}}</option>
{{/}}

//end  
Run Code Online (Sandbox Code Playgroud)

如果不清楚请告诉我,我知道一个可怜的问题是眼睛疼痛.我会尽快编辑.谢谢.

gon*_*uki 5

根据您在此应用程序/用例上控制的部分,您有两种可能的修复方法:修改JSON数据以包含此类根节点,将该根节点添加到您的数据中.

对于两种解决方案,需要对胡须模板进行如下修改:

{{#options}}
    <option value="{{CountryIsoAlpha3Code}}">{{CountryName}}</option>
{{/options}}
Run Code Online (Sandbox Code Playgroud)

现在,您可以直接包裹数据的服务器上或者在您结束,然后getJSON调用会喜欢本作的第二个解决方案(为第一位,取代{options: data}只有包装data).假设您无法控制服务器端,我将使用第二个,因为该API由其他人修复/强制执行:

$.getJSON("jsonresponse.jsonp", function(data) { 
    var tpl = tmpl.mustache,
        html = '';

    html = mustache.render(tpl, {options: data});
}
Run Code Online (Sandbox Code Playgroud)