Article directory
applet project
1. Define the template.
Create a new folder under the project root directory: templates
, which is used to store templates.
Create a new folder under the folder templates: temp
, and create a new file under temp: temp.wxml
and temp.wxss
.
In temp.wxml, templates are <template name=""></template>
defined .
2. Create a new page.
Create a new folder under the root directory of the applet: test
, and create a new Page: under the folder test test
.
3. Use the template in the target page.
The wxml file of the target page is <import src=""/>
imported by the wxml file of the template.
The wxml file for the target page is created by <template is=""></template>
using a template.
The wxss file of the target page must pass @import ""
the wxss file of the import template.
The main files involved in the code are:
- templates/temp/temp.wxml
- templates/temp/temp.wxss
- pages/test/test.json
- pages/test/test.wxml
- pages/test/test.wxss
- pages/test/test.js
templates/temp/temp.wxml
<!-- 定义模板 -->
<template name="my-template">
<view class="user-box">
<image class="avatar" src="{
{avatarUrl}}"/>
<view class="username">{
{username}}</view>
</view>
</template>
templates/temp/temp.wxss
.user-box{
text-align: center;
}
.user-box .avatar{
width: 300rpx;
height: 300rpx;
border-radius: 50%;
}
.user-box .username{
font-size: 48rpx;
font-family:fantasy;
color: #1761d8;
height: 80rpx;
line-height: 80rpx;
}
pages/test/test.json
{
"usingComponents": {
},
"navigationBarBackgroundColor": "#eee",
"navigationBarTextStyle": "black",
"navigationBarTitleText": "我的"
}
pages/test/test.wxml
<import src="/templates/temp/temp.wxml"/>
<view class="test-container">
<template is="my-template" data="{
{...user}}"></template>
</view>
pages/test/test.wxss
@import "/templates/temp/temp.wxss";
.test-container{
height: 100%;
background: #eee;
}
pages/test/test.js
Page({
data:{
user:{
username:"Mr Duck",
avatarUrl:"/static/images/avatar.png"
}
}
})
Related Links
WXML Syntax Reference for Custom Components in Mini Programs
>Template
WXML Syntax Reference>References