1.先看官方文档
模板
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 /> 模块。
2.自己在程序中实验
新建template文件夹,里面可以放模板的结构和样式。
myTemplate.wxml里面写模板自定义内容如下:
<template name="myTmp">
<view>
<view>这是我自定义的模板内容</view>
</view>
</template>
在小程序某个页面中引入和使用模板:
<import src="/template/myTemplate/myTemplate.wxml"/>
<view class="otherContainer">
<!-- 测试模板 -->
<view>测试使用模板</view>
<template is="myTmp"></template>
</view>
这样模板最基本的用法就实现了
假如你在myTemplate.wxss文件中写了模板的样式,在小程序某个使用了模板的页面对应的.wxss文件中引入就i可以使用模板的样式了。
@import '模板对应.wxss文件路径'
动态往模板中注入数据:(谁使用模板谁就往里面注入数据)
<template is="myTmp" data="{{...person}}"></template>