微信小程序> 微信小程序(十二)实战——小程序模板template的使用,以及传递集合数据

微信小程序(十二)实战——小程序模板template的使用,以及传递集合数据

浏览量:2545 时间: 来源:开猿节流

如下图,我们经常做这样的列表页,课程搜索结果页和课程列表页结构是完全一样的,非常适合使用模板来完成页面搭建。

这样我们就不用写那些重复的代码了,而且修改界面的时候也只需要改动模板一个地方

WXML提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用。

小程序

一、定义模板

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

"pages/template/personCourseTmp",小程序

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

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

<template name="personCourseItemTmp"></template>

4.那我们开始实现吧,建模板2个文件

1.personCourseTmp.wxml

<template name="personCourseItemTmp"><!-- 显示 --><view  wx:if="{{mentor_image_uri==null}}"><image class="widget_arrow" src="http://dev.cfo-mentor.com/menter/public/assets/images/avatar_default.png" mode="aspectFill"></image></view><view wx:else><image class="widget_arrow" src="{{mentor_image_uri}}" mode="aspectFill"></image></view><view class='info'>姓名:{{mentor_name}}</view><view class='info'>职位:{{career}}</view><view class='info'>公司:{{company_name}}</view><view class='info'>地区:{{address}}</view><view class='info'>擅长:{{mentor_skills}}</view><navigator url='../../pages/info/info?user_id={{user_id}}'>详情</navigator><view class='hr'></view></template>

2.样式文件personCourseTmp.wxss


.name{text-align: center;} .widget_arrow{   margin-top: 20px;  height: 200px;  width: 200px;  margin-left: 25%;} .info{  font-size:14px }.info_border{  height: 200px;  width: 200px;  border: 8px solid red; }navigator{  margin: 0 auto;  height: 40px;  width: 90%;  margin-top: 20px;   margin-bottom: 20px;  background-color: green;  line-height: 40px;  text-align: center;}.hr{  height: 0;  width: 100%;  border: 1px solid green;}

那我们如何在页面上使用呢,引入样式文件和视图文件

比如我们要在.wxss上面引入样式文件

@import "../template/personCourseTmp.wxss";

只需要在.wxss里面加入上面的代码

我们要在.wxml上面引入视图文件

<import src="../template/personCourseTmp.wxml" />


<block wx:for="{{message}}" wx:key="id">        <template is="personCourseItemTmp" data="{{...item}}"></template></block>

<template is=''  "    data=" "></template> 

 此时的is用来进行判断  data是要传入模板中的数据...eg   ...(spread运算符) 

传数据时item前面加三个点... 模板里面就不需要写item了。

注意

import作用域,其仅仅引用目标文件中template。如:

C import B                              B import A

C中可以使用B定义的template,在B中可以使用A定义的template,但是C不能使用A定义的template。


版权声明

即速应用倡导尊重与保护知识产权。如发现本站文章存在版权问题,烦请提供版权疑问、身份证明、版权证明、联系方式等发邮件至197452366@qq.com ,我们将及时处理。本站文章仅作分享交流用途,作者观点不等同于即速应用观点。用户与作者的任何交易与本站无关,请知悉。

产品经理

手机 : 13312967497

擅长 : 小程序流量变现

扫码领取礼包

最新资讯

热门模板

  • 头条
  • 搜狐
  • 微博
  • 百家
  • 一点资讯
  • 知乎