当前位置: 代码迷 >> 综合 >> 微信小程序学习之Template模板开发
  详细解决方案

微信小程序学习之Template模板开发

热度:70   发布时间:2024-02-28 19:10:47.0

WXML提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用。使用 name 属性,作为模板的名字。然后在 <template/> 内定义代码片段,使用 is 属性,声明需要的使用的模板,然后将模板所需要的 data 传入。

基本用途:

(1)作为一般View显示。例如:(赋值时,加...)

<template is="tpt_func_model_h" data="{ {...modelFuncList[0]}}"></template>

(2)作为List列表的ItemView显示。例如:(赋值时,不加...)

<template is="tpt_func_model_h" data="{ {item}}"></template>

 

引用方式:

(1)import方式,可以在该文件中使用目标文件定义的 template。

<!-- 引用模板列表 -->

<import src="/pages/templates/templates" />

(2)include方式,相当于是拷贝到 include 位置,常用于引用自定义的HeaderView或者FooterView。(类似于Android中的include引用方式)

  <include src="/pages/my/addressList/addressList.wxml"></include>

备注:import导入模板,include用于引入一般View。

 

基本实例:

一、模板创建templates.wxml代码如下:

<!-- 竖版功能Item模板 -->

<template name="tpt_func_model_v">

  <view class="container_v justify_center align_center">

    <image src="{ {imageURL}}" style="height: 50rpx; width: 50rpx;"></image>

    <text style="font-size: 30rpx; margin-top: 10rpx;">{ {title}}</text>

  </view>

</template>

 

<!-- 横版功能Item模板 -->

<template name="tpt_func_model_h">

  <view class="container_h align_center">

    <image src="{ {imageURL}}" style="height: 50rpx; width: 50rpx; margin-right: 20rpx;" class="grow_0"></image>

    <text style="font-size: 30rpx;"  class="grow_1">{ {title}}</text>

    <image src="/images/icon_toright.png" style="height: 30rpx; width: 30rpx; margin-right: 20rpx;"  class="grow_0"></image>

  </view>

</template>

附加,templates.wxss代码内容如下:

.container_v {

  display: flex;

  flex-direction: column;

}

.container_h {

  display: flex;

  flex-direction: row;

}

.justify_center {

  justify-content: center;

}

.justify_between {

  justify-content: space-between;

}

.align_center {

  align-items: center;

}

.align_between {

  align-content: space-between;

}

.grow_0 {

  flex-grow: 0;

}

.grow_1 {

  flex-grow: 1;

}

.bg_white {

  background-color: white;

}

 

二、把模板引用到相应的布局里并使用。

<!-- 引用模板列表 -->

<import src="/pages/templates/templates" />

<!-- 使用相应的模板 -->

<template is="tpt_func_model_h" data="{ {...modelFuncList[0]}}"></template>

 

  相关解决方案