The dynamic data in WXML comes from the data of the corresponding Page.
Simple Binding
Data binding uses the Mustache syntax (double curly brackets) to wrap the variables. It can be used for the following:
Content
<view> {{ message }} </view>
Page({
data: {
message: 'Hello MINA!'
}
})
Component Properties (must be enclosed in double quotes)
<view id="item-{{id}}"> </view>
Control Properties (must be enclosed in double quotes)
<view wx:if="{{condition}}"> </view>
Page({
data: {
condition: true
}
})
Keywords (must be enclosed in double quotes)
True: Boolean-type true.
false: Boolean-type false.
<checkbox checked="{{false}}"> </checkbox>
Note:
Do not directly write checked="false". Its computing result is a string which represents a true value when converted to a Boolean value.
Operations
You can implement simple operations in {{}}. This syntax supports the following methods:
Ternary Operations
<view hidden="{{flag ? true : false}}"> Hidden </view>
Arithmetic Operations
<view> {{a + b}} + {{c}} + d </view>
Page({
data: {
a: 1,
b: 2,
c: 3
}
})
The content in view is 3 + 3 + d.
Logical Judgments
<view wx:if="{{length > 5}}"> </view>
String Operations
<view>{{"hello" + name}}</view>
Page({
data:{
name: 'MINA'
}
})
Data path Operations
<view>{{object.key}} {{array[0]}}</view>
Page({
data: {
object: {
key: 'Hello '
},
array: ['MINA']
}
})
Combinations
You can also directly implement combinations in Mustache syntax to build new objects and arrays.
Arrays
<view wx:for="{{[zero, 1, 2, 3, 4]}}"> {{item}} </view>
Page({
data: {
zero: 0
}
})
The end result is the array [0, 1, 2, 3, 4].
Objects
<template is="objectCombine" data="{{for: a, bar: b}}"></template>
Page({
data: {
a: 1,
b: 2
}
})
The end result is the object {for: 1, bar: 2}.
You can also use the extended operator ... to extend the object.
<template is="objectCombine" data="{{...obj1, ...obj2, e: 5}}"></template>
Page({
data: {
obj1: {
a: 1,
b: 2
},
obj2: {
c: 3,
d: 4
}
}
})
The end result is the object {a: 1, b: 2, c: 3, d: 4, e: 5}.
If the object’s key and value are identical, this can be indirectly expressed.
<template is="objectCombine" data="{{foo, bar}}"></template>
Page({
data: {
foo: 'my-foo',
bar: 'my-bar'
}
})
The end result is the object {foo: 'my-foo', bar:'my-bar'}.
Any combination of the above methods is allowed, but if there are cases where identical variable names occur, the latter will overwrite the former, such as:
<template is="objectCombine" data="{{...obj1, ...obj2, a, c: 6}}"></template>
Page({
data: {
obj1: {
a: 1,
b: 2
},
obj2: {
b: 3,
c: 4
},
a: 5
}
})
The end result is the object {a: 5, b: 3, c: 6}.
Note:
If there are spaces between curly brackets and quotes, the content is ultimately parsed into a string.
<view wx:for="{{[1,2,3]}} ">
{{item}}
</view>
equivalent to
<view wx:for="{{[1,2,3] + ' '}}">
{{item}}
</view>
Was this page helpful?