# Templates

FXML provides templates (template) that allow defining code snippets within templates and then invoking them in different locations.

# 1. Defining Templates

Use the name attribute as the template's name. Then define the code snippet inside <template/>, for example:

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

# 2. Using Templates

Use the is attribute to declare the template to be used, then pass the required data to the template, for example:

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

The is attribute can use Mustache syntax to dynamically determine which specific template to render:

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

# 3. Template Scope

Templates have their own scope and can only use data passed via data and the <fts/> module defined in the template definition file.

© FinClip with ❤ , Since 2017