微信小程序 Template
模板
WXML提供模板(Template),可以在模板中定義代碼片段,然后在不同的地方使用??梢员WC格式以及數(shù)據(jù)的相同。
1-定義模板
使用`<template name="tempName"></template>`標(biāo)簽定義模板,并將模板名稱命名為tempName,賦值給屬性name。在標(biāo)簽內(nèi)部,定義模板結(jié)構(gòu)。如下:
<!-- template.wxml --><!-- index: int msg: string time: string--><template name="msgItem"> <view> <text> {{index}}: {{msg}} </text> <text> Time: {{time}} </text> </view></template>2-使用模板
使用<template is="tempName" />標(biāo)簽,在需要使用模板的地方。如果要用到j(luò)s文件中的數(shù)據(jù),則需要添加data屬性。如下:
<!-- template.wxml --><template is="msgItem" data="{{...item}}"/><template is="msgItem" data="{{...item}}"/><template is="msgItem" data="{{...item}}"/>此時在頁面上就會重復(fù)顯示三次相同的信息。data中的數(shù)據(jù),來源于js文件,如下:<!-- template.js -->Page({ data: { item: { index: 0, msg: 'this is a template', time: '2016-09-15' } }})3-is屬性
is屬性不僅可以靜態(tài)的指向渲染的模板,也可以使用Mustache語法,來動態(tài)決定具體需要渲染哪個模板。如下:
<!-- template.wxml -->// templates<template name="odd"> <view> odd </view></template><template name="odd"> <view> even </view></template>// is屬性使用Mustache語法動態(tài)渲染template<block wx:for="{{[1, 2, 3, 4,5]}}"> <template is="{{item % 2 == 0 ? 'even' : 'odd'}}" /></block>如上代碼,則會在頁面中根據(jù)條件來顯示odd 或是 even
4-模板的引用
如上都是在同一個wxml文件中定義和引用模板,而模板的定義和引用是可以分開的。即在一個文件中定義模板,而在其他一個或多個文件wxml文件中都可以使用定義好的模板。
從外部文件中引用模板,使用import src="templateUrl" />標(biāo)簽。同樣使用is屬性來指向要引用的標(biāo)簽。
如目錄如下:
-pages |--index |--index.js |--index.json |--index.wxml |--index.wxss |--template |--template.js |--template.json |--template.wxml |--template.wxss
要在index.wxml中使用template中定義的模板,則需要先在index中利用import來導(dǎo)入該模板:
<!-- index.wxml --><import src="../template/template.wxml"<template is="msgItem" data={{...indexData}}// 使用的是自己js文件中的數(shù)據(jù)要注意import作用域,其僅僅引用目標(biāo)文件中template。如:C import B,B import A,在C中可以使用B定義的template,在B中可以使用A定義的template,但是C不能使用A定義的template。
新聞熱點(diǎn)
疑難解答