WXML提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用。官方API
一层 template 的使用
使用name属性,作为模板的名字。然后在 template 内定义代码片段,如:
<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'
}
}
})
也可以用单独的参数传值,单独的参数传值的时候,参数中间用逗号隔开,如
<template is="msgItem" data="{{ index,msg,time }}"/>
data:{
index: 0,
msg: 'this is a template',
time: '2016-09-15'
}
如果template单独放在一个文件夹里面,在其他 .wxml 页面调用它的时候先导入放 template 标签的 .wxml 如
<import src="../common/common.wxml"></import>
两层 template +wx:for的使用
定义模板文件 common.wxml
<template name="board-tem" >
<view wx:for="{{ arra }}" >
<block wx:for="{{ item }}" wx:for-item="items" wx:key="items.key">
<template is="inner-tem" data="{{ items }}"></template>
</block>
</view>
</template>
<template name="inner-tem">
<navigator url="../item/item?key={{ items.key }}">
<view >
<text >{{ items[0] }}</text>
<text >{{ items[1] }}</text>
<text >{{ items[2] }}</text>
</view>
</navigator>
</template>
使用模板文件 index.wxml
<import src="../common/common.wxml"></import>
<template is="board-tem" data="{{ arra }}"></template>
index.js内容
data:{
arra:[['a','b','c'],['1','2','3'],['A','B','C']]
},