Template

The axml provides template, where the code snippet can be defined for invoking elsewhere.

It is recommended to use template to introduce template snippet because template specifies the action scope and uses only the data imported. If the data in the template does not change, the UI of the snippet will not be re-rendered.

Define Template

Use the name attribute to declare template name and then define code snippet within <template/>.

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

Use Template

Use the is attribute to declare the required template and then introduce the required data. For example:

copy
<template is="msgItem" data="{{...item}}"/>
copy
Page({
  data: {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2019-04-19',
    },
  },
});

The is attribute allows using the Mustache syntax to decide dynamically which template to render.

copy
<template name="odd">
  <view> odd </view>
</template>
<template name="even">
  <view> even </view>
</template>

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

Template Action Scope

The template has an action scope and can use the data introduced by "data". Except for the data directly introduced by "data", it is possible to use the onXX event to bind page logic for function handling. Below are the sample codes:

copy
<!-- templ.axml -->
<template name="msgItem">
    <view>
        <view>
            <text> {{index}}: {{msg}} </text>
            <text> Time: {{time}} </text>
        </view>
        <button onTap="onClickButton">onTap</button>
    </view>
</template>
copy
<!-- index.axml -->
<import src="./templ.axml"/>
<template is="msgItem" data="{{...item}}"/>
copy
Page({
  data: {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2019-04-22'
    }
  },
  onClickButton(e) {
    console.log('button clicked', e)
  },
});