微信小程序 Template详解及简单实例

微信小程序 Template

模板

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

1-定义模板

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

<!-- 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属性。如下:

<!-- 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语法,来动态决定具体需要渲染哪个模板。如下:

<!-- 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属性来指向要引用的标签。
如目录如下:

-pages
  |--index
    |--index.js
    |--index.json
    |--index.wxml
    |--index.wxss
  |--template
    |--template.js
    |--template.json
    |--template.wxml
    |--template.wxss

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

<!-- 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。

参考

微信小程序文档-框架-视图层-WXML-模板

微信小程序文档-框架-视图层-WXML-引用

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!