WeChat Open Platform

Mini Programs Documentation

Templates

WXML provides templates. Code snippets can be defined in templates, then called in different places.

Definition templates

A name attribute is used as the template name. Then code snippets are defined in <template/>, for example:

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

Using templates

The template that needs to be used is declared using the is attribute, then the data required by the template is imported. For example:

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

The is attribute can use Mustache syntax to dynamically determine the specific template that requires rendering.

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

Template scope

Templates have their own scope, they can only use imported data.