aloisdg
aloisdg

Reputation: 23521

How can I render a plain array with mustache.js?

I am using mustache for template rendering and I face this case:

JSON

{
  "header": "Colors",
  "colors": ["red", "green", "blue"]
}

Mustache template

<h1>{{header}}</h1>
<ul>
{{#colors}}
    <li>{{???}}</li>
{{/colors}}
</ul>

HTML

The HTML rendered should be

<h1>Colors</h1>
<ul>
    <li>red</li>
    <li>green</li>
    <li>blue</li>
</ul>

What should be {{???}}? I tried {{this}}, {{colors}}, {{color}} without success so far.

You can use mustache on their demo.

Upvotes: 1

Views: 732

Answers (2)

Fissure King
Fissure King

Reputation: 1270

From the docs:

When looping over an array of strings, a . can be used to refer to the current item in the list.

View:

{
  "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
}

Template:

{{#musketeers}}
* {{.}}
{{/musketeers}}

Output:

* Athos
* Aramis
* Porthos
* D'Artagnan

Upvotes: 2

aloisdg
aloisdg

Reputation: 23521

The answer is {{.}}! In Unix world . means current, self. See Dot (command)

Mustache template updated

<h1>{{header}}</h1>
<ul>
{{#colors}}
    <li>{{.}}</li>
{{/colors}}
</ul>

Upvotes: 2

Related Questions