Dmitry
Dmitry

Reputation: 4373

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

Upvotes: 8

Views: 16452

Answers (2)

maxbeatty
maxbeatty

Reputation: 9325

If the purpose of <hr/> is purely for style, why not use a CSS selector like :not(:last-child)?

JavaScript:

var tpl = "<ul>{{#employees}}<li>{{firstName}} {{lastName}}</li>{{/employees}}</ul>",
        data = {
  "employees": [
    {"firstName": "John", "lastName": "Smith"},
    {"firstName": "John", "lastName": "Doe"},
    {"firstName": "Jane", "lastName": "Doe", "last": true}    
   ]
},
    html = Mustache.to_html(tpl, data);

document.write(html);

CSS:

li:not(:last-child) {
    border-bottom: 1px solid blue;
}

Here's a working jsFiddle to see it in action

Upvotes: 10

danott
danott

Reputation: 963

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.

Upvotes: 22

Related Questions