Joseph
Joseph

Reputation: 119847

Mustache.js - know if a list only has a single item

currently i'm looping through using mustache when i came across the display of authors..

{{#authors}}{{.}}, {{/authors}} //loop through each author names in authors array

the issue is the comma at the end. i prefer the data (JSON from server) untouched. is there a way in mustache to know if you are in the last iteration (and not append a comma) or know if you are in the first iteration (and not prepend a comma)

Upvotes: 1

Views: 780

Answers (1)

Larry K
Larry K

Reputation: 49114

Not tested!

Overview: add a prefix of ", " for all but the first name.

Template:

{{#beatles}}
  {{name}}
{{/beatles}}

Initialize:

window.app.first_flag = true; // initialize
// assumes that the app has created the window.app object/hash to 
// hold the app's data

View:

 {
  "beatles": [
    { "firstName": "John", "lastName": "Lennon" },
    { "firstName": "Paul", "lastName": "McCartney" },
    { "firstName": "George", "lastName": "Harrison" },
    { "firstName": "Ringo", "lastName": "Starr" }
  ],
  "name": function () {
     var n = this.firstName + " " + this.lastName,
         prefix = ", ";

     if (window.app.first_flag) {
       window.app.first_flag = false;
       prefix = "";
     }
     return prefix + n; 
  }
}

Upvotes: 1

Related Questions