微信小程序中的 WXML 提供了模板(template)功能,你可以在模板中定义代码片段,然后在不同的地方调用这些代码片段。
定义模板
使用 name 属性来给模板命名。然后在<template/>标签内编写代码片段,例如:
<!--
index: int
msg: string
time: string
-->
<template name="msgItem">
<view>
<text> {{index}}: {{msg}} </text>
<text> Time: {{time}} </text>
</view>
</template>
使用模板
使用 is 属性来声明你需要使用的模板,然后把模板需要的数据通过 data 传入,例如:
<template is="msgItem" data="{{...item}}"/>
Page({
data: {
item: {
index: 0,
msg: 'this is a template',
time: '2016-09-15'
}
}
})
is 属性还可以使用 Mustache 语法,来动态决定具体渲染哪个模板:
<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 /> 模块。