[轉]微信小程序-template模板使用


本文轉自:http://blog.csdn.net/u013778905/article/details/59646241

 

如下圖,我在做華企商學院小程序的時候,課程搜索結果頁和課程列表頁結構是完全一樣的,這時就非常適合使用模板來完成頁面搭建。實現一次定義,到處使用。

這里寫圖片描述這里寫圖片描述

模板

一、定義模板

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的寫法,itemwx:for當前項,... 是展開運算符,在模板中不需要再{{item.courseName}} 而是直接{{courseName}}

三、模板樣式

1、在新建模板的時候同時新建一個courseList.wxss 的文件,與CSS同樣的寫法控制樣式。 2、在需要使用模板的頁面 .wxss文件中import進來;或者直接在app.wxss中引入,這樣只需要一次引入,其他文件就不用引入了。

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM