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

时间:2012-11-20 19:58:06

标签: 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

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

//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  

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

1 个答案:

答案 0 :(得分:5)

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

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

{{#options}}
    <option value="{{CountryIsoAlpha3Code}}">{{CountryName}}</option>
{{/options}}

现在,您要么直接将数据包装在服务器上,然后getJSON调用就像第二个解决方案一样(对于第一个解决方案,请更换只有{options: data}的{​​{1}}包装器。假设您无法控制服务器端,我将使用第二个,因为该API由其他人修复/强制执行:

data