Skip to content

Template

WXML provides templates, in which code snippets can be defined and then called from different places.

Define template

Use the name attribute as the name of the template. Then define the code snippet in <template/>, such as:

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

Use template

Use the is attribute to declare the template to be used, and then pass the data required by the template, as shown in the following code:

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

The is attribute can use Mustache syntax to dynamically determine which specific template needs to be rendered:

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>

Template scope

The template has its own scope and can only use the data passed in by data and the <wxs /> module defined in the template definition file.