Sam
Sam

Reputation: 855

Mustache iterate Object of array

I am looking for iterating list of objects of arrays

Here is my sample object

var Categories =    {
      "communication": [
        {
          "id": "communication_001",
          "category": "communication",
          "lastModified": "4 Day ago"
        },
        {
          "id": "communication_002",
          "category": "communication",
          "lastModified": "1 Day ago"
        }
      ],
      "social": [
        {
          "id": "social_001",
          "category": "social",
          "lastModified": "2 Day ago"
        }
      ],
      "storage": [
        {
          "id": "storage_001",
          "category": "storage",
          "lastModified": "3 Day ago"
        }
      ]
    }

here I am compling with mustache

var htmlTemplate= Mustache.render(template, { connectors: Categories });

so what will be my template for compiling?

Suggest me the mustache template.

Upvotes: 3

Views: 4718

Answers (1)

moondaisy
moondaisy

Reputation: 4491

A possible template:

{{#connectors}}
        Communication<br>
    {{#communication}}
        {{id}} - {{category}} - {{lastModified}}<br>
    {{/communication}}
    <br><br>Social<br>
    {{#social}}
        {{id}} - {{category}} - {{lastModified}}<br>
    {{/social}}
    <br><br>Storage<br>
    {{#storage}}
        {{id}} - {{category}} - {{lastModified}}<br>
    {{/storage}}
{{/connectors}}

This generates this:

Communication
communication_001 - communication - 4 Day ago
communication_002 - communication - 1 Day ago


Social
social_001 - social - 2 Day ago


Storage
storage_001 - storage - 3 Day ago

To iterate in the list I'm using sections this will behave differently depending on if the list is or isn't empty:

  • Empty list: the sections won't be rendered
  • Non-empty list: the sections will be rendered once for on each one of the elements of the list, the context of the section is set to the current item allowing you to call it's properties and loop through the list.

But you can do many more things inside of the template so you should check the documentation.

Upvotes: 3

Related Questions