微信小程序中的template模板怎么用(template,微信小程序,编程语言)

时间:2024-05-03 04:04:23 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

微信小程序 template模板详解

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

微信小程序中的template模板怎么用

模板

一、定义模板

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

注意:

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

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

<templatename="courseLeft"><navigatorurl="../play/play?courseUuid={{courseUuid}}&isCompany={{isCompany}}"><viewclass="itemmr26"><imagesrc="{{imagePath}}"mode="aspectFill"></image><viewclass="course-title"><textclass="title">{{courseName}}</text><textclass="author">-{{teacherName}}</text></view><viewclass="course-infoclearfix"><viewclass="fl"><textclass="play">{{playCount}}</text></view><viewclass="fr"><textclass="grade">{{score}}</text></view></view><viewwx:if="{{studyProgress}}"class="tip-completed">{{studyProgress}}</view></view></navigator></template><templatename="courseRight"><navigatorurl="../play/play?courseUuid={{courseUuid}}&isCompany={{isCompany}}"><viewclass="item"><imagesrc="{{imagePath}}"mode="aspectFill"></image><viewclass="course-title"><textclass="title">{{courseName}}</text><textclass="author">-{{teacherName}}</text></view><viewclass="course-infoclearfix"><textclass="playfl">{{playCount}}</text><textclass="gradefr">{{score}}</text></view><viewwx:if="{{studyProgress}}"class="tip-completed">{{studyProgress}}</view></view></navigator></template>

二、使用模板

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

<importsrc="../../templates/courseList.wxml"/>

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

<blockwx:for="{{courseList}}"><templateis="{{index%2===0?'courseLeft':'courseRight'}}"data="{{...item}}"></template></block>

注意:

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

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

<templatewx:if="{{index%2===0}}"is="courseLeft"data="{{...item}}"></template><templatewx:elseis="courseRight"data="{{...item}}"></template>

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

三、模板样式

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

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

@importurl("../template/courseList.wxss");
 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:微信小程序中的template模板怎么用的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:微信小程序怎么实现数据遍历下一篇:

7 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18