Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional loop in mustache.js

How can I output <hr> after every iteration except last one with mustache.js. I tried javascript for loop but I couldn't get rid of last <hr>. (Some people suggest using handlebars.js but I would like stay with mustache.)

Here is my json (the list gets bigger as more employees get added)

    {
      employees: [
        {firstName: "John", lastName: "Smith"},
        {firstName: "John", lastName: "Doe"},
        {firstName: "Jane", lastName: "Doe"}    
       ]
    }

I want this html output:

John Smith
<hr>
John Doe
<hr>
Jane Doe
like image 474
Dmitry Avatar asked Feb 01 '12 01:02

Dmitry


1 Answers

Looking at the Mustache Manual, you'll want to use what's referred to as "Inverted Sections". From the manual:

An inverted section begins with a caret (hat) and ends with a slash. That is {{^person}} begins a "person" inverted section while {{/person}} ends it.

While sections can be used to render text one or more times based on the value of the key, inverted sections may render text once based on the inverse value of the key. That is, they will be rendered if the key doesn't exist, is false, or is an empty list.

To utilize this, you could add an extra attribute to the last employee to distinguish it.

JSON:

{
  "employees": [
    {"firstName": "John", "lastName": "Smith"},
    {"firstName": "John", "lastName": "Doe"},
    {"firstName": "Jane", "lastName": "Doe", "last": true}    
   ]
}

Mustache Template:

{{#employees}}
  {{firstName}} {{lastName}}
  {{^last}}
    <hr />
  {{/last}}
{{/employees}}

This is very similar to what the Mustache Demo showcases, using the "first" attribute on the first object in the array of colors.

like image 139
danott Avatar answered Sep 21 '22 15:09

danott