本文为大家分享了微信小程序模板template的使用方法,供大家参考,具体内容如下
效果图
以MUI的实例首页和列表页面为实例


通过上图,可以看出两个页面的列表部分很相近,以每行作为单元制作模板。
template模板
1、模板存放的位置以及使用模板页面存放的位置

template模板的WXML
<!--右侧无箭头 -->
<template name="listNone">
 <view class="tui-menu-list">
 <navigator url="{{item.url}}">
 <block>
 <text>{{item.title}}</text>
 </block>
 </navigator>
 </view>
</template>
<!--右侧有箭头 -->
<template name="list">
 <view class="tui-menu-list tui-youjiantou">
 <navigator url="{{item.url}}">
 <block>
 <text>{{item.title}}</text>
 </block>
 </navigator>
 </view>
</template>
注意:上边在同一个WXML文件内创建了两个模板,一个右侧有箭头,一个右侧无箭头,以name名识别。 template模板的WXSS
.tui-menu-list{
 line-height: 80rpx;
 color: #555;
 font-size: 35rpx;
 padding: 0 0rpx 0 10px;
 position: relative;
}
在index页面使用template模板
WXML
<import src="../../template/list.wxml"/>
<view class="tui-fixed">
 <scroll-view style="height:100%;" scroll-y="true">
 <template wx:for="{{menu}}" is="list" data="{{item}}"></template>
 </scroll-view>
</view>- 用import 将模板引入;
- 使用模板,template 的is 属性和模板中:name 属性对应,表示你要使用的具体模板,data 属性是模板中要使用的数据,注意数据结构要相同;
- 可以直接循环模板,需要也可以在模板外加一层进行循环。
WXSS
此处将WXSS引入到全局!
@import "./template/list.wxss";- 直接使用import 引入列表的WXSS;
- 此代码可以放在当前页面的WXSS(index.wxss)中,也可以放在全局wxss(app.wxss)中 ;
- 建议:如果项目需要大量使用一个模板,WXSS引入到全局,减少代码量;如果项目只是很少地方使用模板,可以在需要的页面引入WXSS。
在list页面使用template模板
WXML
<import src="../../template/list.wxml"/>
<view class="tui-list-box">
 <view class="tui-list-head">右侧无箭头</view>
 <template wx:for="{{menu}}" is="listNone" data="{{item}}"></template>
</view>
<view class="tui-list-box">
 <view class="tui-list-head">右侧有箭头</view>
 <template wx:for="{{menu}}" is="list" data="{{item}}"></template>
</view>
<view class="tui-list-box-raduis">
 <view class="tui-list-head">圆角列表</view>
 <template wx:for="{{menu}}" is="list" data="{{item}}"></template>
</view>
总结
- 在一个项目中需要在多处页面使用类似的模块,就需要创建模板—-减少代码量,同时代码高度复用;
- 在同一个WXML文件中创建多个类似的模板用name属性来区别;
- 模板WXSS在全局引入和在使用页面引入的区别在于模板的使用量;
- 使用 import 引入模板 WXML 和 WXSS ;
- 通过template 标签使用模板,template 标签的 is 属性与模板的 name 属性对应,data 属性代表传入模板的数据。
DEMO下载
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。