微信小程序使用模板template

微信小程序使用模板template,可以定义template模板,然后在不同的地方进行调用以及代码复用。

.WXML模板的使用

  1. 首先创建你的template模板文件目录,然后创建 xxx.wxml文件。
    在这里插入图片描述

  1. 把你的代码模板放入到 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 属性 是你的模板 名称


  1. 在你要用模板代码的.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模板的使用

  1. 首先创建你的template模板文件目录,然后创建 xxx.wxss文件。
    在这里插入图片描述

  1. 把你的代码模板放入到 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;
}


  1. 在你要用模板代码的.wxss文件中,引用模板文件
/* 引用模板.wxss文件;(最好用相对路径) */
@import "post-item/post-item-template.wxss";

效果图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值