2012-02-01 148 views
8

如何在每次迭代後輸出<hr>,除了最後一次使用mustache.js。我試過JavaScript的循環,但我無法擺脫最後<hr>。 (有人建議使用handlebars.js但我想留小鬍子。)mustache.js中的條件循環

這裏是我的JSON(名單很爲得到補充更多的員工更大)

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

我想這個HTML輸出:

John Smith 
<hr> 
John Doe 
<hr> 
Jane Doe 

回答

21

看着Mustache Manual,你會想要使用被稱爲「倒置段」的東西。從手冊開始:

倒置部分以插入符號(帽子)開始,以斜線結尾。 即{{^ person}}開始一個「人物」倒立部分,而 {{/ person}}結束它。

雖然各部分可用於根據 一次或多次呈現文本,但鍵的值,反轉部分可能會根據鍵的相反值 呈現一次文本。也就是說,如果 鍵不存在,爲假或爲空列表,它們將被呈現。

要利用此功能,您可以向最後一名員工添加一個額外的屬性以區分它。

JSON:

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

髭模板:

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

這是非常相似於什麼Mustache Demo陳列櫃,使用的顏色陣列中的第一對象上的 「第一」 屬性。

10

如果<hr/>的目的純粹是爲了風格,爲什麼不使用像:not(:last-child)這樣的CSS選擇器?

的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