首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JSON数组进入Mustache

JSON数组进入Mustache
EN

Stack Overflow用户
提问于 2017-12-02 13:15:18
回答 1查看 667关注 0票数 0

我正在尝试从我的JSON数组中获取要在Mustache模板中显示的数据。我已经这样做了几个小时了,但我仍然不知道我错过了什么(或者可能有太多?)。

请注意,这个特殊的任务要求我使用let而不是var

下面是我的代码:

HTML:

代码语言:javascript
复制
<script id="mustacheTemplate" type="x-tmpl-mustache">
<ul id="output">
{{#items}}
    <li>{{title}}{{description}}</li>
{{/items}}
</ul>
</script>

JSON:

代码语言:javascript
复制
{ "items": [
    {"title": "Mulan",
    "description": "Based on the Chinese legend of Hua Mulan, and was Disney's 36th animated feature."
    },
    {"title": "Beauty and the Beast",
    "description": "An adaptation of the fairy tale about a monstrous-looking prince and a young woman who fall in love."
    },
    {"title": "Aladdin",
    "description": "Aladdin is a street-urchin who lives in Agrabah, a large and busy town, long ago with his faithful monkey friend Abu."
    ]},
}

Javascript:

代码语言:javascript
复制
console.log($);


$(document).ready(function() {

    $.getJSON('../data/content.json', result);

    function result (data, status){
        console.log(data);

        let template = $("#mustacheTemplate").html();

        let content = data.items;

        let output = Mustache.render(template, content);
        console.log(output);

        $('#output').html(output);
    });
});
EN

回答 1

Stack Overflow用户

发布于 2017-12-02 13:42:47

在传递render时,需要传递数据而不是data.item

我在这里评论了你的$.getJSON('../data/content.json', result);

它可能会对你有所帮助

代码语言:javascript
复制
function result (data, status){
      data={ "items": [
    {"title": "Mulan",
    "description": "Based on the Chinese legend of Hua Mulan, and was Disney's 36th animated feature."
    },
    {"title": "Beauty and the Beast",
    "description": "An adaptation of the fairy tale about a monstrous-looking prince and a young woman who fall in love."
    },
    {"title": "Aladdin",
    "description": "Aladdin is a street-urchin who lives in Agrabah, a large and busy town, long ago with his faithful monkey friend Abu."}
    ]
};
        //console.log(data);

        let template = $("#mustacheTemplate").html();
//console.log(template)
        let content = data;

        let output = Mustache.render(template, content);
        //console.log(output);

        $('#output').html(output);
        }
$(document).ready(function() {

    //$.getJSON('../data/content.json', result);

    
   result(1,5);
});
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<script id="mustacheTemplate" type="x-tmpl-mustache">
<ul>
{{#items}}
    <li>{{title}}{{description}}</li>
{{/items}}
</ul>
</script>

<div id="output"></div>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47604838

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档