微信小程序使用模板template,可以定义template模板,然后在不同的地方进行调用以及代码复用。
.WXML模板的使用
- 首先创建你的template模板文件目录,然后创建
xxx.wxml
文件。
- 把你的代码模板放入到
post-item-template.wxml
文件中
<!-- name属性是 模板名称 -->
<template name="postItem">
<view class='post-container'>
<view class='post-author-date'>
<image wx:if="{{true}}" class='post-author' src='{{item.avatar}}'></image>
<text class='post-date'>{{item.date}}</text>
</view>
<text class='post-title'>{{item.title}}</text>
<image class='post-image' src='{{item.imgSrc}}'></image>
<text class='post-content'>{{item.content}}</text>
<view class='post-like'>
<image class='post-like-image' src='../../images/icon/wjx.png'></image>
<text class='post-like-font'>{{item.collection}}</text>
<image class='post-like-image' src='../../images/icon/view.png'></image>
<text class='post-like-font'>{{item.reading}}</text>
</view>
</view>
</template>
注: 这里的 name
属性 是你的模板 名称
- 在你要用模板代码的
.wxml
文件中,引用模板文件
<!-- 引入template 模板,必须有闭合的标签;(这里相对路径也行,绝对路径也行) -->
<import src="post-item/post-item-template.wxml" />
<block wx:for="{{posts_key}}" wx:for-item="item" wx:for-index="index" wx:key="">
<!-- template -->
<!-- 这里is的值:模板的名字,后边的data表示,循环所获得的数据中的每一项 -->
<template is="postItem" data="{{item}}" />
</block>
注: 一定要有 is
属性,其值是 你template模板所定义的 name
的值,这里的 data 属性,是因为这个案例功能是循环,所以表示的是所获得的数据中的 每一项。
.WXSS模板的使用
- 首先创建你的template模板文件目录,然后创建
xxx.wxss
文件。
- 把你的代码模板放入到
post-item-template.wxss
文件中
.post-author-date {
/* margin-top: 10rpx;
margin-bottom: 20rpx;
margin-left: 10rpx; */
margin: 10rpx 0rpx 20rpx 10rpx;
}
.post-author {
width: 60rpx;
height: 60rpx;
vertical-align: middle;
}
.post-date {
margin-left: 20rpx;
vertical-align: middle;
margin-bottom: 5px;
font-size: 26rpx;
}
.post-title {
font-size: 34rpx;
font-weight: 600;
color: #333;
margin-bottom: 10px;
margin-left: 10px;
}
.post-image {
margin-left: 16px;
width: 100%;
height: 500rpx;
margin: auto 0;
margin-bottom: 15px;
}
.post-content {
color: #666;
font-size: 28rpx;
margin-bottom: 20rpx;
margin-left: 20rpx;
letter-spacing: 2rpx;
line-height: 40rpx;
}
.post-like {
font-size: 13px;
flex-direction: row;
line-height: 16px;
margin-left: 10px;
}
.post-like-image {
height: 16px;
width: 16px;
margin-right: 8px;
/* 垂直排列居中 */
vertical-align: middle;
}
.post-like-font {
vertical-align: middle;
margin-right: 20px;
}
- 在你要用模板代码的
.wxss
文件中,引用模板文件
/* 引用模板.wxss文件;(最好用相对路径) */
@import "post-item/post-item-template.wxss";