Mustache.js 也可以使用迴圈!


Non-Empty Lists

If the person key exists and is not nullundefined, or false, and is not an empty list the block will be rendered one or more times.
When the value is a list, the block is rendered once for each item in the list. The context of the block is set to the current item in the list for each iteration. In this way we can loop over collections.
View:
{
  "stooges": [
    { "name": "Moe" },
    { "name": "Larry" },
    { "name": "Curly" }
  ]
}
Template:
{{#stooges}}
<b>{{name}}</b>
{{/stooges}}
Output:
<b>Moe</b>
<b>Larry</b>
<b>Curly</b>

When looping over an array of strings, a . can be used to refer to the current item in the list.
View:
{
  "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
}
Template:
{{#musketeers}}
* {{.}}
{{/musketeers}}
Output:
* Athos
* Aramis
* Porthos
* D'Artagnan
If the value of a section variable is a function, it will be called in the context of the current item in the list on each iteration.
View:
{
  "beatles": [
    { "firstName": "John", "lastName": "Lennon" },
    { "firstName": "Paul", "lastName": "McCartney" },
    { "firstName": "George", "lastName": "Harrison" },
    { "firstName": "Ringo", "lastName": "Starr" }
  ],
  "name": function () {
    return this.firstName + " " + this.lastName;
  }
}
Template:
{{#beatles}}
* {{name}}
{{/beatles}}
Output:
* John Lennon
* Paul McCartney
* George Harrison
* Ringo Starr

留言

熱門文章