WeChat Open Platform

Mini Programs Documentation

Data binding

The dynamic data in WXML all comes from the corresponding Page data.

Simple binding

Data binding uses Mustache syntax (double brace) to package variables. It can act on:

Content

<view> {{ message }} </view>
Page({
  data: {
    message: 'Hello MINA!'
  }
})

Component properties (need to be in double quotes)

<view id="item-{{id}}"> </view>
Page({
  data: {
    id: 0
  }
})

Control properties (need to be in double quotes)

<view wx:if="{{condition}}"> </view>
Page({
  data: {
    condition: true
  }
})

Keywords (need to be in double quotes)

True: if boolean type is true, a true value is represented.

false: If boolean type is false, a false value is represented.

<checkbox checked="{{false}}"> </checkbox>

Pay special attention: Do not directly write checked="false", its calculation result is a string. A true value is represented after conversion to boolean type.

Mathematical operations

Simple mathematical operations can be performed within {{}}, the following methods are supported:

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
  }
})

Content in view is 3 + 3 + d.

Logical judgment

<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']
  }
})

Composition

New objects or arrays can be composed or configured directly in Mustache.

Arrays

<view wx:for="{{[zero, 1, 2, 3, 4]}}"> {{item}} </view>
Page({
  data: {
    zero: 0
  }
})

Final array composition [0, 1, 2, 3, 4]

Object

<template is="objectCombine" data="{{for: a, bar: b}}"></template>
Page({
  data: {
    a: 1,
    b: 2
  }
})

The final object composition is {for: 1, bar: 2}

The extension operator ... expands an object

<template is="objectCombine" data="{{...obj1, ...obj2, e: 5}}"></template>
Page({
  data: {
    obj1: {
      a: 1,
      b: 2
    },
    obj2: {
      c: 3,
      d: 4
    }
  }
})

The final object composition is {a: 1, b: 2, c: 3, d: 4, e: 5}

If the object key and value are the same, this can also be expressed indirectly.

<template is="objectCombine" data="{{foo, bar}}"></template>
Page({
  data: {
    foo: 'my-foo',
    bar: 'my-bar'
  }
})

The final object composition is {foo: 'my-foo', bar:'my-bar'}

Note: The methods above can be composed at random, but the front will overwrite the back if any variable names are the same, for example:

<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 final object composition is {a: 5, b: 3, c: 6}