微信小程序template模板的使用


参考: 模板

WXML提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用。

这里我们使用模板template改写微信小程序构建新闻列表中的示例代码

新建模板

新建post-item-template目录,并创建post-item-template.wxml和post-item-template.wxss文件
在这里插入图片描述

移植代码到模板中

post.wxml中代码如下,现在将post-container节点的代码作为一个模板。
在这里插入图片描述

将post-container节点的代码移植到post-item-template.wxml文件中

<!-- post-item-template.wxml -->

<template name="postItem">
  <view class="post-container">
    <view class="post-author-date">
      <image 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/chat.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>

post.wxss中相关的代码移植到post-item-template.wxss中

.post-container{
    flex-direction:column;
    display:flex;
    margin-top:20rpx;
    margin-bottom:40rpx;
    margin-left: 0rpx;
    background-color:#fff;
    border-bottom: 1px solid #ededed;
    border-top: 1px solid #ededed;
    padding-bottom: 5px;
}

.post-author-date{
    margin-top:10rpx;
    margin-bottom: 20rpx;
    margin-left: 10px;
}

.post-author{
    width:60rpx;
    height:60rpx;
    vertical-align: middle;
}

.post-date{
    margin-left: 20px;
    vertical-align: middle;
}

.post-image{
    width:100%;
    height:340rpx;
    margin:auto 0;
    margin-bottom: 15px;
}

.post-date{
    font-size:26rpx;
    margin-bottom: 10px;
}
.post-title{
    font-size:34rpx;
    font-weight: 600;
    color:#333;
    margin-bottom: 10px;
    margin-left: 10px;
}
.post-content{
    color:#666;
    font-size:28rpx;
    margin-bottom:20rpx;
    margin-left: 20rpx;
    letter-spacing:2rpx;
    line-height: 40rpx;
}
.post-like{
    font-size:13px;
    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;
}

引入模板

在post.wxml中引入wxml模板:

<import src="post-item-template/post-item-template.wxml" />

在这里插入图片描述

在post.wxss中引入wxss模板

@import "post-item-template/post-item-template.wxss";

在这里插入图片描述

使用模板

在post.wxml中使用模板

  <block wx:for="{{posts_key}}" wx:for-item="item" wx:key="postId" wx:for-index="idx">
    <!--//template-->
      <template is="postItem" data="{{item}}" />
  </block>

改造代码

在这里插入图片描述

在模板的wxml文件中,每个引用的数据,都需要使用item。

在item前加3个点,就可以将上面所有item去除,如下:
在这里插入图片描述

发布了446 篇原创文章 · 获赞 67 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/hongxue8888/article/details/104768336
今日推荐