如何使用嵌套对象为JSON数据创建Mustache模板?

时间:2022-10-15 14:31:08

I have this JSON data

我有这个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":[

         ]
      }
]

and my code is

我的代码是

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

I am using JavaScript and Mustache Templates to display all the items with its name, description and picture. But I am having trouble accessing through nested arrays. How do I retrieve these nested values?

我使用JavaScript和Mustache模板显示所有项目的名称,描述和图片。但我无法通过嵌套数组访问。如何检索这些嵌套值?

1 个解决方案

#1


1  

If you want to iterate over a top-level array you should refer it as {{#.}} .. {{./}} Also you have some typos, look, that's how your template will work:

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

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

#1


1  

If you want to iterate over a top-level array you should refer it as {{#.}} .. {{./}} Also you have some typos, look, that's how your template will work:

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

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