AXML provides templates
, you can define code snippets in a template, and call them in different places.
Note: we recommend you to use the
template
method to introduce the template fragment because template
specifies its scope and only uses the data passed by data
. If the data
of the template
does not change, the fragment UI will not be re-rendered.Define a template
Use the name attribute to specify the template name, and define a code snippet in <template/>
.
<!--
index: int
msg: string
time: string
-->
<template name="msgItem">
<view>
<text> {{index}}: {{msg}} </text>
<text> Time: {{time}} </text>
</view>
</template>
Use a template
Use the is
attribute to declare the required template and pass the required data
.
<template is="msgItem" data="{{...item}}"/>
Page({
data: {
item: {
index: 0,
msg: 'this is a template',
time: '2019-04-19',
},
},
});
Use the is
attribute to dynamically determine the specific template to be rendered based on Mustache syntax.
<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 scope and can only use the data passed by data
. In addition, you can also bind page logic to process functions by calling onXX
events. As shown in the following code snippet:
<!-- 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)
},
});