小程序中模板的使用

模板:wxml提供模板(template),可以在模板中定義代碼段,然後在不同的地方進行使用。

1.定義模板

使用name屬性,作爲模板的名字,然後在<template></template>內定義代碼片段

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

2.使用模板

使用is屬性,聲明需要的使用的模板,然後將模板所需要的data傳入

<template is="msgItem" data="{{...item}}"/>
item表示模板所需要的一些數據

3.is屬性可以是Mustache語法,來動態決定具體需要渲染哪個模板。

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

 模板文件的引用

wxml提供兩種文件引用方式import和include

import的使用

import 可以在該文件中使用目標文件定義的template

在item.wxml中定義一個叫item的template:

<template name="item">
  <text>{{text}}</text>
</template>

在index.wxml文件中進行使用

<import src="item.wxml"/> 表示在此位置導入item.wxml文件的內容
is  表示導入的是name值爲item的模板  data表示此模板中需要用到的數據
<template is="item" data="{{text: 'forbar'}}"/>

inclue

include 可以將目標文件除了<template></template> ,<wxs/>外的整個代碼引入,相當於是拷貝到include位置

<!-- index.wxml -->
在index.wxml中進行引入header.wxml和footer.wxml
<include src="header.wxml"/>
<view> body </view>         等同於====<view> header </view>
<include src="footer.wxml"/>            <view> body </view>
                                    <view> footer </view>

這裏是header.wxml
<!-- header.wxml -->
<view> header </view>



這裏是footer.wxml
<!-- footer.wxml -->
<view> footer </view>

 

發佈了84 篇原創文章 · 獲贊 0 · 訪問量 1814
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章