tencent cloud

Feedback

WXML Template

Last updated: 2024-11-21 18:28:34
    WeiXin Markup Language (WXML) is a set of markup language for framework design. It can be used with basic components and event systems to construct page structures. Find the app.json file in the root directory and open it in the IDE. Add a new line pages/wxml/index above the line pages/index/index and save file. After the simulator is refreshed automatically, you can find the pages/wxml/index.WXML file in the editor. This document describes how to modify this file.

    Overview

    The suffix of the WXML file is .wxml. Open the pages/wxml/index.WXML file and you will find that the WXML statements are similar to the HTML syntax if you are familiar with the HTML coding.
    <!--pages/wxml/index.wxml-->
    
    <text>pages/wxml/index.wxml</text>
    The basic syntax of WXML without any logical features is as follows:
    <!-- Add comment here-->
    
    <Tag name Attribute name 1="Attribute value 1" Attribute name 2="Attribute value 2" ...> ...</Tag name>
    A complete WXML statement consists of an opening tag and a closing tag, which can wrap either content or other WXML statements. This is similar to HTML. The difference is that WXML statements must be strictly closed, otherwise, a compilation error might occur.
    <text>hello world
    
    
    <!--
    text is not closed, resulting in a compile error:
    VM148:2 ./pages/wxml/index.wxml
    end tag missing, near text
    > 1 | <text>hello world
    | ^
    -->
    Tags can have attributes that provide more information about the WXML element. Attributes are always defined in the opening tag. Most of the attributes are in key="value" format except for some special ones. Note that attributes in WXML are case-sensitive, which means that class and Class are different attributes in WXML. The following is an example of text tags:
    <!-- A simple text tag-->
    <text>hello world</text>
    
    <!-- view contains text tags -->
    <view>
    <text>hello world</text>
    </view>
    An example of image tags with attributes is shown below:
    <image class="userinfo-avatar" src="./image/a.png" ></image>

    Data binding

    UI page displays must be dynamically updated in response to data variations at specific times or alterations caused by user actions. This necessitates incorporating dynamic page rendering capabilities during mini program execution. In Web development, developers use JavaScript to update pages in real time through DOM manipulation API. In mini program, use this data binding provided by the WXML to implement this.
    Here is an example:
    Modify the content of the pages/wxml/index.wxml file a little bit, as shown below:
    <!--pages/wxml/index.wxml-->
    <text>Current time: {{time}}</text>
    After the file is saved and refreshed in the IDE, the simulator does not display the current time, because we have not set any initial value for time. Open the pages/wxml/index.js file and add time: in the data curly brackets (new Date()).toString(),as shown below:
    // pages/wxml/index.js
    Page({
    /**
    * Initial page data
    */
    data: {
    time: (new Date()).toString()
    },
    })
    After saving and refreshing, simulator displays the correct current time, and the compile time will be updated.
    WXML binds the data object attributes in the WXML file and the corresponding JavaScript file by {{variable name}}.
    In order to keep it simple, the following format is used to show this coding logic. You can use the first comment part to show the data structure in the script file corresponding to WXML, as shown below:
    <!--
    {
    time: (new Date()).toString()
    }
    -->
    <text> Current time: {{time}}/text>
    Attribute values can also be changed dynamically and must be wrapped in double quotes, as shown below:
    <!-- Correct coding -->
    <text data-test="{{test}}"> hello world</text>
    
    
    <!-- Wrong coding -->
    <text data-test={{test}}> hello world </text >
    Please note that the variable is case-sensitive, that is, {{name}} and {{Name}} are two different variables, as shown below:
    <!--
    {
    w: 'w',
    W: 'W'
    }
    -->
    
    
    <view>{{w}}</view>
    <view>{{W}}</view>
    
    
    <!-- Output
    w
    W
    -->
    Note that variables or variables is set to will not be synchronized to the wxml, as shown below:
    <!--
    {
    var2: undefined,
    var3: null,
    var4: "var4"
    }
    -->
    
    
    <view>{{var1}}</view>
    <view>{{var2}}</view>
    <view>{{var3}}</view>
    <view>{{var4}}</view>
    
    
    <!--
    Output:
    null
    var4
    -->
    For more details about data binding, see Chapter 3.

    Logical syntax

    You can implement dynamic rending through {{variable name}}in WXML and implement simple operations in {{ }}.
    Ternary operation:
    <!-- Display page content conditionally based on whether a is equal to 10 or not -->
    <text>{{ a === 10? "variable a is equal to 10": "variable a is not equal to 10"}}</text>
    Arithmetic operation:
    <!--
    { a: 1, b: 2, c: 3 }
    -->
    
    
    <view> {{a + b}} + {{c}} + d </view>
    
    
    <!-- Output 3 + 3 + d -->
    Similar to arithmetic operation, it also supports string concatenation, as shown below:
    <!--
    { name: 'world' }
    -->
    
    
    <view>{{"hello " + name}}</view>
    
    
    <!-- Output hello world -->
    You can also place numbers, strings or arrays in the {{ }}, as shown below:
    <text>{{[1,2,3]}}</text>
    
    <!-- Output 1,2,3 -->
    
    
    
    <text>{{"hello world"}}</text>
    
    <!-- Output hello world -->

    Logical judgement

    In WXML, use wx:if="{{condition}}" to determine whether or not to render this code block:
    <view wx:if="{{condition}}"> True </view>
    Use wx:elif and wx:else to add an "else" block:
    <view wx:if="{{length > 5}}"> 1 </view>
    <view wx:elif="{{length > 2}}"> 2 </view>
    <view wx:else> 3 </view>
    Because wx:if is a control attribute, you must add it to a tag. To judge multiple component tags at once, you can use a <block/> tag to package multiple components together and use the wx:if control attribute above.
    <block wx:if="{{true}}">
    <view> view1 </view>
    <view> view2 </view>
    </block>

    List rendering

    In a component, by binding an array using the wx:for control attribute, you can use the data of the array items to re-render this component. The subscript variable name of the current item of the default array defaults to index, and the variable name of the current item of the array defaults to item:
    <!-- `array` is an array -->
    <view wx:for="{{array}}">
    {{index}}: {{item.message}}
    </view>
    
    <!-- Corresponding script file
    Page({
    data: {
    array: [{
    message: 'foo',
    }, {
    message: 'bar'
    }]
    }
    })
    -->
    You can use wx:for-item to specify the variable name of the array's current element and use wx:for-index to specify the variable name of the array's current subscript:
    <view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName">
    {{idx}}: {{itemName.message}}
    </view>
    Similar to block wx:if, you can use wx:for on a <block/> tag to render a structural block containing multiple nodes:
    <block wx:for="{{[1, 2, 3]}}">
    <view> {{index}}: </view>
    <view> {{item}} </view>
    </block>
    If the positions of list items dynamically change or new items are added to the list and you want the items in the list to retain their features and statuses (such as the content input in <input/> and the selection status of <switch/>), you must use wx:key to specify the unique identifiers of the items in the list. The wx:key value is provided in either of the following formats:
    1. String: Represents an attribute of an item in the for loop array. The value of this attribute must be a unique string or number in the list and cannot dynamically change.
    2. Reserved keyword this: Represents the item itself in the for loop. This indicates that the item itself is a unique string or number. For example:
    When a data change triggers re-rendering at the rendering layer, the components that have keys are corrected. The framework ensures that they are reordered, rather than recreated. This ensures the components retain their statuses and improves the efficiency of list rendering.
    <switch wx:for="{{objectArray}}" wx:key="unique" > {{item.id}} </switch>
    <button bindtap="switch"> Switch </button>
    <button bindtap="addToFront"> Add to the front </button>
    
    
    <switch wx:for="{{numberArray}}" wx:key="*this" > {{item}} </switch>
    <button bindtap="addNumberToFront"> Add Number to the front </button>
    Page({
    data: {
    objectArray: [
    {id: 5, unique: 'unique_5'},
    {id: 4, unique: 'unique_4'},
    {id: 3, unique: 'unique_3'},
    {id: 2, unique: 'unique_2'},
    {id: 1, unique: 'unique_1'},
    {id: 0, unique: 'unique_0'},
    ],
    numberArray: [1, 2, 3, 4]
    },
    switch: function(e) {
    const length = this.data.objectArray.length
    for (let i = 0; i < length; ++i) {
    const x = Math.floor(Math.random() * length)
    const y = Math.floor(Math.random() * length)
    const temp = this.data.objectArray[x]
    this.data.objectArray[x] = this.data.objectArray[y]
    this.data.objectArray[y] = temp
    }
    this.setData({
    objectArray: this.data.objectArray
    })
    },
    addToFront: function(e) {
    const length = this.data.objectArray.length
    this.data.objectArray = [{id: length, unique: 'unique_' + length}].concat(this.data.objectArray)
    this.setData({
    objectArray: this.data.objectArray
    })
    },
    addNumberToFront: function(e){
    this.data.numberArray = [ this.data.numberArray.length + 1 ].concat(this.data.numberArray)
    this.setData({
    numberArray: this.data.numberArray
    })
    }
    })

    Templates

    WXML provides templates, where you can define code snippets and then call them in different places. Use the name attribute to specify the name of the template. Then define that code snippet inside <template/>:
    <template name="msgItem">
    <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
    </view>
    </template>
    Use the is attribute to declare the template to be used. Then, pass the data needed by the template. For example:
    <!--
    item: {
    index: 0,
    msg: 'this is a template',
    time: '2016-06-18'
    }
    -->
    
    
    <template name="msgItem">
    <view>
    <text> {{index}}: {{msg}} </text>
    <text> Time: {{time}} </text>
    </view>
    </template>
    
    
    <template is="msgItem" data="{{...item}}"/>
    
    <!-- Output
    0: this is a template Time: 2016-06-18
    -->
    Use is to dynamically decide which template to be rendered, as shown below:
    <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>
    
    
    
    <!-- Output
    odd
    even
    odd
    even
    odd
    -->

    Reference

    WXML provides two referencing methods import and include.
    import can use the template defined by the target file in the current file, for example, a template named item is defined in item.wxml:
    <!-- item.wxml -->
    <template name="item">
    <text>{{text}}</text>
    </template>
    By referencing item.wxml in index.wxml, you can use the item template:
    <import src="item.wxml"/>
    
    <template is="item" data="{{text: 'forbar'}}"/>
    The concept of "scope" is used for import references. This means that the reference will import the template defined in the target file but not the template imported by the target file. For example, C references B and B references A, and the template defined by B can be used in C, and the template defined by A can be used in B, but C cannot use the template defined by A, as shown below:
    <!-- A.wxml -->
    <template name="A">
    <text> A template </text>
    </template>
    <!-- B.wxml --><import src="a.wxml"/><template name="B"> <text> B template </text></template>
    <!-- C.wxml -->
    <import src="b.wxml"/>
    
    <template is="A"/> <!-- An alarm will be triggered, as template A is not defined in b -->
    
    <template is="B"/>
    include can introduce the entire code excluding <template/> <wxs/>. This is equivalent to copying the code to the location of include. For example:
    <!-- index.wxml -->
    <include src="header.wxml"/>
    
    <view> body </view>
    
    <include src="footer.wxml"/>
    <!-- header.wxml -->
    <view> header </view>
    <!-- footer.wxml -->
    <view> footer </view>

    Common attributes

    The attributes that are supported by all wxml tags are common attributes.
    Attribute
    Type
    Definition
    Description
    id
    String
    Unique identifier of the component
    Unique for entire page
    class
    String
    Style class for the component
    The style class defined in the corresponding WXSS
    style
    String
    Inline style of the component
    The inline style that can be set dynamically
    hidden
    Boolean
    Whether the component is displayed
    Default display for all components
    data-*
    Any
    Custom attribute
    When an event is triggered on the component, it will be sent to the event handler function.
    bind*/catch*
    EventHandler
    Component Event
    ‌-
    
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support