【问题标题】:How do I render Mustache templates with JSON with no root node如何使用没有根节点的 JSON 渲染 Mustache 模板
【发布时间】:2012-11-21 14:13:29
【问题描述】:

我正在构建一个小页面,它使用 jquery 的 getJSON 调用 API,然后使用 mustache 模板呈现数据(至少这是计划)。但是,我的 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  

如果不清楚,请告诉我,我知道一个糟糕的问题会让人眼疼。我会尽快编辑。谢谢。

【问题讨论】:

    标签: jquery json jsonp mustache


    【解决方案1】:

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

    对于这两种解决方案,必须对 mustache 模板进行如下修改:

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

    现在您要么直接在服务器上包装数据或,然后在第二个解决方案中getJSON 调用将是这样的(对于第一个,替换@987654323 @ 包装器只有data)。我将使用第二个假设您无法控制服务器端,因为该 API 是由其他人固定/授权的:

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

    【讨论】:

    • 工作就像一个魅力。非常感谢你。我很乐意为此给你一个额外的 +25 !我也认为我会改变我的答案以更好地反映主要问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2015-03-11
    • 2012-05-26
    相关资源
    最近更新 更多