Shah Erhan
Shah Erhan

Reputation: 593

Freemarker iterate nested array/object

I'm new to Freemarker and currently I'm stuck on getting nested output for metalsElements

metals = 
{
  "name": "BRONZE",
  "state": "SOLID",
  "density": 25,
  "price": 120,
  "rarity": "COMMON",
  "metalsElements": [
    {
      "metalsInfoId": 30,
      "element": "copper",
      "percentage": "87",
      "id": 26
    },
    {
      "metalsInfoId": 30,
      "element": "tin",
      "percentage": "12",
      "id": 27
    },
    {
      "metalsInfoId": 30,
      "element": "nickel",
      "percentage": "1",
      "id": 28
    }
  ],
  "id": 30
}

I've tried using the codes below but still haven't successful

<ul>
  <#list metals.metalsElements as key>
    <li>${key}</li>
  </#list>
</ul>

and

<ul>
  <#list metalsElements as key,val>
    <li>${key}</li>
  </#list>
</ul>

Anybody has the solution? Thanks

Upvotes: 0

Views: 565

Answers (2)

Ori Marko
Ori Marko

Reputation: 58792

You have two loops, one for metalsElements, other for all its attributes:

<ul>
  <#list metals.metalsElements as metalsElement>
    <#list metalsElement as key,value>
      <li>${key}</li><li>${value}</li>
    </#list>
  </#list>
</ul>

Upvotes: 2

Monsieur Merso
Monsieur Merso

Reputation: 2156

In your example key represents inner element of metalsElements array, you'll have to specify concrete properties of this element, like this:

<ul>
  <#list metals.metalsElements as key>
    <li>Element: ${key.element} Percentage: ${key.percentage}</li>
  </#list>
</ul>

You can test your templates online here if you want.

Upvotes: 1

Related Questions