Skip to content

模版

WXML提供模版(template),可以在模版中定義代碼片段,然後在不同的地方調用。

定義模版

使用name内容,作為模版的名字。 然後在<template/>內定義代碼片段,如:

js
<!--
  index: int
  msg: string
  time: string
-->
<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>

使用模版

使用is内容,聲明需要的使用的模版,然後將模版所需要的data傳入,如下代碼所示:

js
<template is="msgItem" data="{{...item}}"/>
js
Page({
  data: {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    }
  }
})

is内容可以使用Mustache語法,來動態决定具體需要渲染哪個模版:

js
<template name="odd">
  <view> odd </view>
</template>
<template name="even">
  <view> even </view>
</template>

<block wx:for="{{[1, 2, 3, 4, 5]}}">
  <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
</block>

模版的作用域

模版擁有自己的作用域,只能使用data傳入的數據以及模版定義文件中定義的<wxs />模塊。