Mustache.js - 知道列表是否只有一个项目

时间:2012-02-17 03:46:39

标签: javascript mustache

目前,当我看到作者的展示时,我正在使用胡子循环..

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

问题是最后的逗号。我更喜欢数据(来自服务器的JSON)。小胡子有没有办法知道你是否在最后一次迭代(而不是附加一个逗号)或者知道你是否在第一次迭代中(而不是在前面添加一个逗号)

1 个答案:

答案 0 :(得分:1)

未经测试!

概述:为除名字之外的所有名称添加“,”前缀。

模板:

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

初始化:

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

查看:

 {
  "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; 
  }
}
相关问题