bpn40441
bpn40441

Reputation: 1

How to create a Mustache template for JSON data with nested objects?

I have this JSON data

    [
      {
         "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?

Upvotes: 0

Views: 1235

Answers (1)

Andrei Hrabouski
Andrei Hrabouski

Reputation: 125

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}}
{{/.}}

Upvotes: 1

Related Questions