微信小程序 模板(template)
作者: --时间: 2025-05-18 01:49:27 阅读量:

微信小程序模板(template)是一种方便重复使用的代码片段,可以大大提高开发效率。以下是使用和定义微信小程序模板的基本方法:

1. 定义模板


使用name属性来定义模板的名称,在<template/>标签内编写代码片段,如下所示:

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

2. 使用模板


使用is属性来声明所需使用的模板,并将必要的数据传入,具体演示请见以下代码:

<template is="msgItem" data="{{...item}}"/>
Page({
  data: {
    item: {
      index: 0,
      msg: 'this is a template',
      time: '2016-09-15'
    }
  }
})

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>

3. 模板的作用域

每个模板都有自己的作用域,只能访问通过data传入的数据。

一套系统全搞定
  • 商家管理
  • 商品管理
  • 订单管理
  • 会员管理
  • 营销中心
  • 供应链入驻
  • 财务管理
  • 支付分账
  • 商城直播
免费试用
更多产品任你选
B2B2C多用户商城系统

类天猫&京东模式系统

了解更多
B2B2B电商交易系统

全渠道订货/采购及经销商管
理数字化系统

了解更多
S2B2B电商交易系统

上下游资源整合数字化解决方

了解更多
企业集采商城系统

中大型企业数字化采购与交易
系统

了解更多
员工福利商城系统

集福利管理、发放于一体的员
工福利商城

了解更多

电话咨询 微信咨询 0元开店