一、WXML 模板语法
目录
1、数据绑定
<!--wxml-->
<view> {{message}} </view>
// page.js
Page({
data: {
message: 'Hello MINA!'
}
})
注意:
- 可以在
{{}}
内进行简单的运算,支持的有如下几种方式:
三元运算、算数运算、逻辑判断、字符串运算等;
花括号和引号之间如果有空格,将最终被解析成为字符串。
2、列表渲染
<!--wxml-->
<view wx:for="{{array}}"> {{item}} </view>
// page.js
Page({
data: {
array: [1, 2, 3, 4, 5]
}
})
注意:
- 使用
wx:for-item
可以指定数组当前元素的变量名; - 使用
wx:for-index
可以指定数组当前下标的变量名; - 使用
wx:key
可以动态渲染列表,此时wx:key
作为列表中项目的唯一的标识符,若是静态列表可忽略wx:key
; - 花括号和引号之间如果有空格,将最终被解析成为字符串。
3、条件渲染
<!--wxml-->
<view wx:if="{{view == 'WEBVIEW'}}"> WEBVIEW </view>
<view wx:elif="{{view == 'APP'}}"> APP </view>
<view wx:else="{{view == 'MINA'}}"> MINA </view>
// page.js
Page({
data: {
view: 'MINA'
}
})
注意:一般来说,wx:if 有更高的切换消耗而 hidden 有更高的初始渲染消耗。因此,如果需要频繁切换的情景下,用 hidden 更好,如果在运行时条件不大可能改变则 wx:if 较好。
4、模板
WXML提供模板(template),可以在模板中定义代码片段,然后在不同的地方调用。
模板的作用域:
模板拥有自己的作用域,只能使用 data 传入的数据以及模板定义文件中定义的 <wxs /> 模块。
(1)、定义模板
使用 name 属性,作为模板的名字。然后在<template/>
内定义代码片段,如:
<template name="msgItem">
<view>
<text> {{index}}: {{msg}} </text>
<text> Time: {{time}} </text>
</view>
</template>
(2)、使用模板:
使用 is 属性,声明需要的使用的模板,然后将模板所需要的 data 传入,如:
<template is="msgItem" data="{{...item}}"/>
Page({
data: {
item: {
index: 0,
msg: 'this is a template',
time: '2016-09-15'
}
}
})
(3)、综合运用
<!--wxml-->
<template name="staffName">
<view>
FirstName: {{firstName}}, LastName: {{lastName}}
</view>
</template>
<template is="staffName" data="{{...staffA}}"></template>
<template is="staffName" data="{{...staffB}}"></template>
<template is="staffName" data="{{...staffC}}"></template>
// page.js
Page({
data: {
staffA: {firstName: 'Hulk', lastName: 'Hu'},
staffB: {firstName: 'Shang', lastName: 'You'},
staffC: {firstName: 'Gideon', lastName: 'Lin'}
}
})
5、引用
WXML 提供两种文件引用方式import
和include
。
(1)、import
- 引用目标文件定义的
template模板;
- 作用域是目标文件中定义的
template
模板;
如:C import B,B import A,在C中可以使用B定义的template
,在B中可以使用A定义的template
,但是C不能使用A定义的template
。
<!-- A.wxml -->
<template name="A">
<text> A template </text>
</template>
<!-- B.wxml -->
<import src="a.wxml"/>
<template name="B">
<text> B template </text>
</template>
<!-- C.wxml -->
<import src="b.wxml"/>
<template is="A"/> <!-- Error! Can not use tempalte when not import A. -->
<template is="B"/>
(2)、include
将目标文件除了 <template/>
<wxs/>
外的整个代码引入。