All Products
Search
Document Center

Template

Last Updated: Feb 04, 2021

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

 
  1. <!--
  2. index: int
  3. msg: string
  4. time: string
  5. -->
  6. <template name="msgItem">
  7. <view>
  8. <text> {{index}}: {{msg}} </text>
  9. <text> Time: {{time}} </text>
  10. </view>
  11. </template>

Use a template

Use the is attribute to declare the required template and pass the required data.

 
  1. <template is="msgItem" data="{{...item}}"/>
 
  1. Page({
  2. data: {
  3. item: {
  4. index: 0,
  5. msg: 'this is a template',
  6. time: '2019-04-19',
  7. },
  8. },
  9. });

Use the is attribute to dynamically determine the specific template to be rendered based on Mustache syntax.

 
  1. <template name="odd">
  2. <view> odd </view>
  3. </template>
  4. <template name="even">
  5. <view> even </view>
  6. </template>
  7. <block a:for="{{[1, 2, 3, 4, 5]}}">
  8. <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/>
  9. </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:

 
  1. <!-- templ.axml -->
  2. <template name="msgItem">
  3. <view>
  4. <view>
  5. <text> {{index}}: {{msg}} </text>
  6. <text> Time: {{time}} </text>
  7. </view>
  8. <button onTap="onClickButton">onTap</button>
  9. </view>
  10. </template>
 
  1. <!-- index.axml -->
  2. <import src="./templ.axml"/>
  3. <template is="msgItem" data="{{...item}}"/>
 
  1. Page({
  2. data: {
  3. item: {
  4. index: 0,
  5. msg: 'this is a template',
  6. time: '2019-04-22'
  7. }
  8. },
  9. onClickButton(e) {
  10. console.log('button clicked', e)
  11. },
  12. });