javascript - 如何为带有嵌套对象的 JSON 数据创建 Mustache 模板?

标签 javascript json mustache

我有这个 JSON 数据

    [
      {
         "item":{

            "name":"some name",
            "description":" someDescription ",
            "price":"6",         
            "image_url":"url"
         },
         "options":[

         ]
      },
       {
         "item":{

            "name":"some name",
            "description":" someDescription ",
            "price":"6",         
            "image_url":"url"
         },
         "options":[

         ]
      }
]

我的代码是

<script id="itemtpl" type="text/template">
{{#items}}
        {{#item}}
        <div class ="item"> 
            <img src = "{{image_url}} alt="Photo of {{menu_item_name}}"/>
            <h3>{{menu_item_name}}</h3>
            <h4>{{menu_item_price}}</h4>
            <p>{{menu_item_description}}</p>
        </div>
        {{/#item}}
{{/items}}
</script>


<script type ="text/javascript">
$(function(){

    $.getJSON('fullmenu.json', function(data) {
            var template = $('#itemtpl').html();
            var html = Mustache.to_html(template, data);
            $('#menu').html(html);
    });//getJSON

});//function

</script>

我正在使用 JavaScript 和 Mustache 模板来显示所有项目及其名称、描述和图片。但我在通过嵌套数组访问时遇到问题。如何检索这些嵌套值?

最佳答案

如果您想迭代顶级数组,您应该将其引用为 {{#.}} .. {{./}} 另外,您还有一些拼写错误,看,这就是您的模板的工作方式:

{{#.}}
        {{#item}}
        <div class ="item"> 
            <img src = "{{image_url}} alt="Photo of {{name}}"/>
            <h3>{{name}}</h3>
            <h4>{{price}}</h4>
            <p>{{description}}</p>
        </div>
        {{/item}}
{{/.}}

关于javascript - 如何为带有嵌套对象的 JSON 数据创建 Mustache 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28031299/

相关文章:

javascript - 由于 webpack 模块解析器而导致 ReactJS 测试文件问题 'cannot find module'

javascript - 如何将json数据发送到可序列化类

mustache 渲染列表如果不为空

javascript - Node.js + Node-MySQL + Express 4 + Mustache

node.js - Expressjs + Handlebars 格式化日期

javascript - 使用 vis.js 更改作为节点的图像颜色

javascript - Base64 数据类型

java - 如何从 Android 中返回 XML 或 JSON 的 url 获取数据

Python:用另一个字符替换转义引号

javascript - 如何在同一个html中多次调用JS函数