13.小程序視圖層的模板

模板

WXML提供模板(template),能夠在模板中定義代碼片斷,而後在不一樣的地方調用。html

定義模板

使用 name 屬性,做爲模板的名字。而後在<template/>內定義代碼片斷,如:this

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

使用模板

使用 is 屬性,聲明須要的使用的模板,而後將模板所須要的 data 傳入,如:spa

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

is 屬性能夠使用 Mustache 語法,來動態決定具體須要渲染哪一個模板:code

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

模板的做用域

模板擁有本身的做用域,只能使用 data 傳入的數據以及模版定義文件中定義的 <wxs /> 模塊。htm

注:使用模板前要先用import導入模板的作用域

相關文章
相關標籤/搜索