如何在小程序中使用template

如何在小程序中使用template,第1张

一、定义模板

1、新建一个template文件夹用来管理项目中所有的模板;

2、新建一个courseList.wxml文件来定义模板;

3、使用name属性,作为模板的名字。然后在内定义代码片段。

注意:

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")

1 可以通过修改CSS样式实现。

2 首先需要将容器元素设置为 display:flex然后设置图片元素的宽度为固定值或百分比,并设裤饥置 margin-right:20px使其与下一个图片之间留有一定的空隙。

3 可以根胡搜返据具体需求修改容器元素和图片元素的CSS样式,以达到想要的效漏滚果。

不支持。小程序官方文档明手岩确指数蔽出,引入的第三方自定义组件,是不可以对其进行CSS样式覆盖的。层叠样式毕毕御表(英文全称:CascadingStyleSheets)是一种用来表现HTML(标准通用标记语言的一个应用)。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12415559.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存