Search code examples
htmlmustachetemplate-engine

How to get root values of array in Mustache's loop representation?


When using Mustache template, loop representation is like this:

Data:

{animals: [
  {name: "cat"}, 
  {name: "dog"}, 
  {name: "pig"}
]}

Template:

{{#animals}}
  <p>{{name}}</p>
{{/animals}}

Result:

<p>cat</p>
<p>dog</p>
<p>pig</p>

But if the values want to use are written under the array directly, how can I access them? What I wrote means,

Data:

{animals: [
  "cat", 
  "dog", 
  "pig"
]}

Result:

<p>cat</p>
<p>dog</p>
<p>pig</p>

To get the result above, how may I write template?

Regards,


Solution

  • Use {{.}} in your view. This refers to the current item in the list being referenced in the template. As you are using an array of strings opposed to an object literal, the content of the array is displayed. If you were using your previous object literal variable, [object][object] would be displayed in your template view.

    Reference: https://github.com/janl/mustache.js/

    Object

    animals: [
      "cat", 
      "dog", 
      "pig"
    ]
    

    View

    {{#animals}}
      <p>{{.}}</p>
    {{/animals}}
    

    Output

    <p>cat</p>
    <p>dog</p>
    <p>pig</p>