微信小程序 Template詳解及簡單實例
微信小程序 Template
模板
WXML提供模板(Template),可以在模板中定義代碼片段,然后在不同的地方使用??梢员WC格式以及數(shù)據(jù)的相同。
1-定義模板
使用`<template name="tempName"></template>`標簽定義模板,并將模板名稱命名為tempName,賦值給屬性name。在標簽內(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" />標簽,在需要使用模板的地方。如果要用到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" />標簽。同樣使用is屬性來指向要引用的標簽。
如目錄如下:
-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作用域,其僅僅引用目標文件中template。如:C import B,B import A,在C中可以使用B定義的template,在B中可以使用A定義的template,但是C不能使用A定義的template。
參考
微信小程序文檔-框架-視圖層-WXML-模板
微信小程序文檔-框架-視圖層-WXML-引用
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
直觀詳細的typescript隱式類型轉(zhuǎn)換圖文詳解
這篇文章主要為大家介紹了直觀詳細的typescript隱式類型轉(zhuǎn)換圖文詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-07-07
JavaScript實現(xiàn)一個Promise隊列小工具
這篇文章主要介紹了JavaScript實現(xiàn)一個Promise隊列小工具,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08

