欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序 template模板详解及实例代码

程序员文章站 2022-05-12 23:24:24
微信小程序 template模板详解 如下图,我在做华企商学院小程序的时候,课程搜索结果页和课程列表页结构是完全一样的,这时就非常适合使用模板来完成页面搭建。实现一次定义...

微信小程序 template模板详解

如下图,我在做华企商学院小程序的时候,课程搜索结果页和课程列表页结构是完全一样的,这时就非常适合使用模板来完成页面搭建。实现一次定义,到处使用。

微信小程序 template模板详解及实例代码微信小程序 template模板详解及实例代码

模板

一、定义模板

1、新建一个template文件夹用来管理项目中所有的模板;
2、新建一个courselist.wxml文件来定义模板;
3、使用name属性,作为模板的名字。然后在<template/>内定义代码片段。

注意:

a.可以看到一个.wxml文件中可以定义多个模板,只需要通过name来区分;

b.模板中的数据都是展开之后的属性。

<template name="courseleft">
  <navigator url="../play/play?courseuuid={{courseuuid}}&iscompany={{iscompany}}">
    <view class="item mr26">
      <image src="{{imagepath}}" mode="aspectfill"></image>
      <view class="course-title">
        <text class="title">{{coursename}}</text>
        <text class="author">- {{teachername}}</text>
      </view>
      <view class="course-info clearfix">
        <view class="fl"><text class="play">{{playcount}}</text></view>
        <view class="fr"><text class="grade">{{score}}</text></view>
      </view>
      <view wx:if="{{studyprogress}}" class="tip-completed">{{studyprogress}}</view>
    </view>
  </navigator>
</template>

<template name="courseright">
  <navigator url="../play/play?courseuuid={{courseuuid}}&iscompany={{iscompany}}">
    <view class="item">
      <image src="{{imagepath}}" mode="aspectfill"></image>
      <view class="course-title">
        <text class="title">{{coursename}}</text>
        <text class="author">- {{teachername}}</text>
      </view>
      <view class="course-info clearfix">
        <text class="play fl">{{playcount}}</text>
        <text class="grade fr">{{score}}</text>
      </view>
      <view wx:if="{{studyprogress}}" class="tip-completed">{{studyprogress}}</view>
    </view>
  </navigator>
</template>

二、使用模板

1、使用 is 属性,声明需要的使用的模板

<import src="../../templates/courselist.wxml"/>

2、将模板所需要的 data 传入,一般我们都会使用列表渲染。

<block wx:for="{{courselist}}">
  <template is="{{index%2 === 0 ? 'courseleft' : 'courseright'}}" data="{{...item}}"></template>
</block>

注意:

a.可以通过表达式来确定使用哪个模板is="{{index%2 === 0 ? 'courseleft' : 'courseright'}}"

或者通过wx:if来确定。index是数组当前项的下标。

<template wx:if="{{index%2 === 0}}" is="courseleft" data="{{...item}}"></template>
<template wx:else is="courseright" data="{{...item}}"></template>

b. data 是要模板渲染的数据,data="{{...item}}" 写法是es6的写法,item是wx:for当前项,... 是展开运算符,在模板中不需要再{{item.coursename}} 而是直接{{coursename}} 。

三、模板样式

1、在新建模板的时候同时新建一个courselist.wxss 的文件,与css同样的写法控制样式。

2、在需要使用模板的页面 .wxss文件中import进来;或者直接在app.wxss中引入,这样只需要一次引入,其他文件就不用引入了。

@import url("../template/courselist.wxss");

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!