Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

WeChat Program Template


May 18, 2021 WeChat Mini Program Development Document


Table of contents


Template


WXML provides templates in which you can define snippets of code and then call them in different places.

Define the template


Use the name attribute as the name of the template. Then <template/>

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

Use a template


Using the is property, declare the template you want to use, and then pass in the data you need for the template, such as:

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

Is properties can use the Mustache syntax to dynamically decide which template needs to be rendered:

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

The scope of the template

The template has its own scope and can only use data that is passed in using data.