微信小程序——template模板的使用

本文深入解析WXML模板的定义与使用,展示如何利用template标签减少代码冗余,实现组件复用,提升小程序开发效率。文章详细介绍了在wxml文件中创建模板、使用import语句引用模板文件以及在wxss中定义样式的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

模板

WXML提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用。当项目需要多次使用同一个布局和样式的时候,就可以考虑使用template(模板)来减少冗余代码。

如何定义以及使用模板

 

wxml模块:

  1. 新建template文件夹,新建wxml。
  2. wxml文件由template标签包裹,并设置template标签名字属性方便调用。
  3. 使用时在对应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;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值