WXML provides templates, in which you can define code snippets and then call them in different places.
Defining a Template
Use the name property to specify the name of the template
. Then, define a code snippet in <template/>. For example:
<template name="msgItem">
<view>
<text> {{index}}: {{msg}} </text>
<text> Time: {{time}} </text>
</view>
</template>
Using the Template
Using the is attribute, declare the template you want to use, and then pass in the data the template needs, for example:
<template is="msgItem" data="{{...item}}"/>
Page({
data: {
item: {
index: 0,
msg: 'this is a template',
time: '2016-09-15'
}
}
})
The is
property can use Mustache syntax to dynamically determine the template to be rendered:
<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
Templates have their own scopes. They can only use the data passed by data and the <wxs /> module defined in the file defined by the template.
Was this page helpful?