微信小程式開發(fā)文檔
/ 微信小程序 模板
微信小程序 模板
模板
WXML提供模板(template),可以在模板中定義代碼片段,然后在不同的地方調(diào)用。
定義模板
使用name屬性,作為模板的名字。然后在<template/>
內(nèi)定義代碼片段,如:
<!-- index: int msg: string time: string --> <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' } } })
is屬性可以使用Mustache語法,在運(yùn)行時來決定具體需要渲染哪個模板:
<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傳入的數(shù)據(jù)。