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

谈谈小程序模板的运用

程序员文章站 2022-05-04 12:28:48
...

谈谈小程序模板的运用

小程序官方文档:

模板

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

定义模板

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

<!--
  index: int
  msg: string
  time: string
-->
<template name="msgItem">
  <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
  </view>
</template>

使用模板

使用 is 属性,声明需要的使用的模板,然后将模板所需要的 data 传入,如:

<template is="msgItem" data="{{...item}}"/>
Page({
  data: {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    }
  }
})

is 属性可以使用 Mustache 语法,来动态决定具体需要渲染哪个模板:

<template name="odd">
  <view> odd </view>
</template>
<template name="even">
  <view> even </view>
</template>

<block wx:for="{{[1, 2, 3, 4, 5]}}">
    <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
</block>

模板的作用域

模板拥有自己的作用域,只能使用 data 传入的数据以及模版定义文件中定义的 <wxs /> 模块。


网上的一点网页博客

WXML提供模板(Template),可以在模板中定义代码片段,然后在不同的地方使用。可以保证格式以及数据的相同。

1-定义模板

使用`<template name="tempName"></template>`标签定义模板,并将模板名称命名为tempName,赋值给属性name。在标签内部,定义模板结构。如下:

1
2
3
4
5
6
7
8
9
10
11
12
<!-- template.wxml -->
<!--
  index: int
  msg: string
  time: string
-->
<template name="msgItem">
  <view>
  <text> {{index}}: {{msg}} </text>
  <text> Time: {{time}} </text>
 </view>
</template>

2-使用模板

使用<template is="tempName" />标签,在需要使用模板的地方。如果要用到js文件中的数据,则需要添加data属性。如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!-- template.wxml -->
 
<template is="msgItem" data="{{...item}}"/>
<template is="msgItem" data="{{...item}}"/>
<template is="msgItem" data="{{...item}}"/>
此时在页面上就会重复显示三次相同的信息。
data中的数据,来源于js文件,如下:
 
<!-- template.js -->
Page({
 data: {
  item: {
   index: 0,
   msg: 'this is a template',
   time: '2016-09-15'
  }
 }
})

3-is属性

is属性不仅可以静态的指向渲染的模板,也可以使用Mustache语法,来动态决定具体需要渲染哪个模板。如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!-- template.wxml -->
 
// templates
<template name="odd">
  <view> odd </view>
</template>
<template name="odd">
  <view> even </view>
</template>
 
// is属性使用Mustache语法动态渲染template
<block wx:for="{{[1, 2, 3, 4,5]}}">
  <template is="{{item % 2 == 0 ? 'even' : 'odd'}}" />
</block>

如上代码,则会在页面中根据条件来显示odd 或是 even

//官方文档没有的小程序引用模板:

4-模板的引用

如上都是在同一个wxml文件中定义和引用模板,而模板的定义和引用是可以分开的。即在一个文件中定义模板,而在其他一个或多个文件wxml文件中都可以使用定义好的模板。
从外部文件中引用模板,使用import src="templateUrl" />标签。同样使用is属性来指向要引用的标签。
如目录如下:

1
2
3
4
5
6
7
8
9
10
11
-pages
  |--index
    |--index.js
    |--index.json
    |--index.wxml
    |--index.wxss
  |--template
    |--template.js
    |--template.json
    |--template.wxml
    |--template.wxss

要在index.wxml中使用template中定义的模板,则需要先在index中利用import来导入该模板:

1
2
3
4
<!-- index.wxml -->
<import src="../template/template.wxml"
<template is="msgItem" data={{...indexData}}
// 使用的是自己js文件中的数据
要注意import作用域,其仅仅引用目标文件中template。如:C import B,B import A,在C中可以使用B定义的template,在B中可以使用A定义的template,但是C不能使用A定义的template。