1. 程式人生 > >微信小程式模板template的使用

微信小程式模板template的使用

WXML提供模板(template),可以在模板中定義程式碼片段,然後在不同的地方呼叫。官方API

一層 template 的使用

使用name屬性,作為模板的名字。然後在 template 內定義程式碼片段,如:

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

使用 is 屬性,宣告需要的使用的模板,然後將模板所需要的 data 傳入,這是利用陣列一次傳三個值,在用陣列傳值的時候,陣列前面加三個 ‘.’,如:

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

也可以用單獨的引數傳值,單獨的引數傳值的時候,引數中間用逗號隔開,如

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

如果template單獨放在一個資料夾裡面,在其他 .wxml 頁面呼叫它的時候先匯入放 template 標籤的 .wxml 如

<import src="../common/common.wxml"></import>

兩層 template +wx:for的使用

定義模板檔案 common.wxml

<template name="board-tem" >
    <view wx:for="{{ arra }}" >
        <block wx:for
="
{{ item }}" wx:for-item="items" wx:key="items.key"> <template is="inner-tem" data="{{ items }}"></template> </block> </view> </template> <template name="inner-tem"> <navigator url="../item/item?key={{ items.key }}"> <view > <text >{{ items[0] }}</text> <text >{{ items[1] }}</text> <text >{{ items[2] }}</text> </view> </navigator> </template>

使用模板檔案 index.wxml

<import src="../common/common.wxml"></import>
<template is="board-tem" data="{{ arra }}"></template>

index.js內容

data:{
    arra:[['a','b','c'],['1','2','3'],['A','B','C']]
    },