模板
WXML提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用。当项目需要多次使用同一个布局和样式的时候,就可以考虑使用template(模板)来减少冗余代码。
如何定义以及使用模板
wxml模块:
- 新建template文件夹,新建wxml。
- wxml文件由template标签包裹,并设置template标签名字属性方便调用。
- 使用时在对应wxml文件通过 import 引用。
<template name="postitem" >
<view class='post-container'>
<view class='post-author-date'>
<image class='post-author' src='/images/xml.jpg'></image>
<text class='post-date'>{{item.date}}</text>
</view>
<text class='post-title'>{{item.title}}</text>
<image wx:if="{{!boolean_show}}" class='post-image' src="{{item.image}}"></image>
<text class='post-content'>{{item.content}}</text>
<view class='post-like'>
<image class='post-like-image' src="{{item.img.view_img}}"></image>
<text class='post-like-font'>{{item.view_num}}</text>
<image class='post-like-image' src="{{item.img.collect_img}}"></image>
<text class='post-like-font'>{{item.collect_num}}</text>
</view>
</view>
</template>
引用template模板的语句实际上只有下面一句, 后面加上 data属性 是为了遍历数组得到数组中的每一个元素对象的每个内容
<template is="postitem" />
<import src="文件路径" />
<!-在需要调用处,通过名字属性调用-->
<block wx:for="{{post_key}}" wx:for-item="item">
<!-- 将postId作为一个属性存放到view标签中,自定义属性data开头 -->
<view catchtap='onPostTap' data-postId="{{item.postId}}" >
<template is="postitem" data="{{item}}" />
</view>
</block>
wxss模块:
1.在template文件夹下新建wxss文件。
2.写入wxss内容。
3.使用时在对应wxml文件通过 @import 引用。
.post-container{
/* 弹性盒子模型 */
display: flex;
flex-direction: column;
margin-top: 20rpx;
margin-bottom: 40rpx;
background-color: #fff;
/* 上下边界 */
border-bottom: 1px solid #ededed;
border-top: 1px solid #ededed;
/* 页边距 */
padding-bottom: 5px;
}
引用语句只有一句 ,不需要通过 import 引用
@import "文件路径";
下面的wxss文件中就已经引用了template文件夹下的wxss文件的内容了,比如上面的 .post-container
@import "文件路径";
swiper{
width:100%;
height:600rpx;
}
swiper image{
width:100%;
height:600rpx;
}