# 列表渲染

当你需要渲染列表时，可以使用 `tt:for`。`tt:for`中绑定了一个数组，默认数组的当前项下标变量名默认为 index，数组的当前项变量名默认为 item。

```html
<view tt:for="{{array}}">
  {{index}}: {{item.message}}
</view>
```

```js
// index.js
Page({
  data: {
    array: [{
      message: 'foo',
    }, {
      message: 'bar'
    }]
  }
})
```

使用 `tt:for-item` 可以指定数组当前元素的变量名，使用 `tt:for-index` 可以指定数组当前下标的变量名。主要用在多个 `tt:for` 嵌套的情况。

```html
<view tt:for="{{array}}" tt:for-index="idx" tt:for-item="itemName">
  {{idx}}: {{itemName.message}}
</view>
```

## block tt:for

你可以将 `tt:for` 用在 `<block/>` 标签上，以渲染一个包含多节点的结构块。例如：

```html
<block tt:for="{{[1, 2, 3]}}">
  <view> {{index}}: </view>
  <view> {{item}} </view>
</block>
```
## block tt:key

如果列表中项目的位置会动态改变或者有新的项目添加到列表中，并且希望列表中的项目保持自己的特征和状态（如 input 中的输入内容，switch 的选中状态），则需要使用 `tt:key` 来指定列表中项目的唯一标识符。

`tt:key` 的值以两种形式提供：

- 形式一：字符串。代表在 for 循环的 array 中 item 的某个 property，该 property 的值需要是列表中唯一的字符串或数字，且不能动态改变。

- 形式二：保留关键字 `*this` 代表在 for 循环中的 item 本身，该形式需要 item 本身是一个唯一的字符串或者数字。

当数据改变触发渲染层重新渲染的时候，系统会校正带有 key 的组件，框架会确保这些组件被重新排序，而不是重新创建，以确保组件保持自身的状态，并且提高列表渲染时的效率。

```html
<switch tt:for="{{objectArray}}" tt:key="unique" style="display: block;"> {{item.id}} </switch>
<button bindtap="switch"> Switch </button>
<button bindtap="addToFront"> Add to the front </button>

<switch tt:for="{{numberArray}}" tt:key="*this" style="display: block;"> {{item}} </switch>
<button bindtap="addNumberToFront"> Add to the front </button>
```

```js
Page({
  data: {
    objectArray: [
      {id: 5, unique: 'unique_5'},
      {id: 4, unique: 'unique_4'},
      {id: 3, unique: 'unique_3'},
      {id: 2, unique: 'unique_2'},
      {id: 1, unique: 'unique_1'},
      {id: 0, unique: 'unique_0'},
    ],
    numberArray: [1, 2, 3, 4]
  },
  switch: function(e) {
    const length = this.data.objectArray.length
    for (let i = 0; i < length; ++i) {
      const x = Math.floor(Math.random() * length)
      const y = Math.floor(Math.random() * length)
      const temp = this.data.objectArray[x]
      this.data.objectArray[x] = this.data.objectArray[y]
      this.data.objectArray[y] = temp
    }
    this.setData({
      objectArray: this.data.objectArray
    })
  },
  addToFront: function(e) {
    const length = this.data.objectArray.length
    this.data.objectArray = [{id: length, unique: 'unique_' + length}].concat(this.data.objectArray)
    this.setData({
      objectArray: this.data.objectArray
    })
  },
  addNumberToFront: function(e){
    this.data.numberArray = [ this.data.numberArray.length + 1 ].concat(this.data.numberArray)
    this.setData({
      numberArray: this.data.numberArray
    })
  }
})

```