WeChat Open Platform

Mini Programs Documentation


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">
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>

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}}"/>
  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 name="even">
  <view> even </view>

<block wx:for="{{[1, 2, 3, 4, 5]}}">
    <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>

Template scope

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