微信小程序 template
模板
WXML提供模板(Template),可以在模板中定義代碼片段,然后在不同的地方使用??梢员WC格式以及數(shù)據(jù)的相同。
1-定義模板
使用``標(biāo)簽定義模板,并將模板名稱(chēng)命名為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-使用模板
使用標(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}}"/> 此時(shí)在頁(yè)面上就會(huì)重復(fù)顯示三次相同的信息。 data中的數(shù)據(jù),來(lái)源于js文件,如下: <!-- template.js --> Page({ data: { item: { index: 0, msg: 'this is a template', time: '2016-09-15' } } })
3-is屬性
is屬性不僅可以靜態(tài)的指向渲染的模板,也可以使用Mustache語(yǔ)法,來(lái)動(dòng)態(tài)決定具體需要渲染哪個(gè)模板。如下:
<!-- template.wxml --> // templates <template name="odd"> <view> odd </view> </template> <template name="odd"> <view> even </view> </template> // is屬性使用Mustache語(yǔ)法動(dòng)態(tài)渲染template <block wx:for="{{[1, 2, 3, 4,5]}}"> <template is="{{item % 2 == 0 ? 'even' : 'odd'}}" /> </block>
如上代碼,則會(huì)在頁(yè)面中根據(jù)條件來(lái)顯示odd 或是 even
4-模板的引用
如上都是在同一個(gè)wxml文件中定義和引用模板,而模板的定義和引用是可以分開(kāi)的。即在一個(gè)文件中定義模板,而在其他一個(gè)或多個(gè)文件wxml文件中都可以使用定義好的模板。
從外部文件中引用模板,使用import src="templateUrl" />標(biāo)簽。同樣使用is屬性來(lái)指向要引用的標(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來(lái)導(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。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
更多微信小程序 template詳解及簡(jiǎn)單實(shí)例相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)!
微信是一款手機(jī)通信軟件,支持通過(guò)手機(jī)網(wǎng)絡(luò)發(fā)送語(yǔ)音短信、視頻、圖片和文字。微信可以單聊及群聊,還能根據(jù)地理位置找到附近的人,帶給大家全新的移動(dòng)溝通體驗(yàn),有需要的小伙伴快來(lái)保存下載體驗(yàn)吧!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)