Template

更新时间:
复制 MD 格式

AXML provides the template tag, which can be used to define code snippets and reuse them in different locations.

Note

You can use the template tag to import template snippets. A template has its own scope and can only use data passed to it through the `data` property. If the data for the template does not change, the UI of the snippet is not re-rendered.

Define a template

You can use the name property to specify the name of the template. Then, you can define the code snippet within the <template/> tag.

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

Use a template

You can use the is property to specify the template to use. Then, you can pass in the required data. For example:

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

You can use Mustache syntax with the is property to dynamically determine which template to render.

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

A template has its own scope and can only use data passed to it through the `data` property. You can also bind page logic to a function using an onXX event. The following code shows an example.

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