Repository: apelegri/wechat-mini-program-wiki
Branch: master
Commit: e0d243f61cd8
Files: 1
Total size: 71.9 KB
Directory structure:
gitextract__stt95yx/
└── README.md
================================================
FILE CONTENTS
================================================
================================================
FILE: README.md
================================================
# WeChat Mini-programs Wiki
### PREFACE
China’s top messaging app WeChat rolled out something quite radical: mini-programs. Embedded apps which require no download, no install. Open, use, share, done!
#### Yes, it's not perfect...
There is large debate – *and many clickbaits* – about how practical these apps are... Indeed the framework provided to developers is only at infancy stage, still limited, and honestly a bit frustrating. Nevertheless Tencent is investing unprecedented resources into the adoption of this channel, building momentum, and opening opportunities to the first-movers. We believe that these hackers may find quick-wins if they dare to give it a try.
Got ideas of services you would like to deploy in WeChat asap? Have basic knowledge of Javascript and want to experiment with this framework? Got lost in the Google translation of the doc? Need a small boost to decrypt what is possible or not? Hello and welcome.
#### Why this Wiki
Finding your way through the official doc is not easy. In fact, it requires a lot of trial/errors, some research on open-source code and many assumptions to get something done. You have been banging your head on the wall. We get it.
Our mission is to help creative entrepreneurs build great tech products. We will help you take the small steps.
The content below is not a translation of the documentation and will surely be outdated fast. It is simply our contribution to help any one get started and build a cool WeChat Mini-program fast. **Do it now.**
### Get in touch
Are you working on a mini-program? Do [reach out to us](http://lewagon.com/shanghai) if you’d like to share your work, meet our crew, ask for help!
### Contribute to this Wiki
If you want to contribute, you can send a Pull Request [here](https://github.com/apelegri/wechat-miniprogram-wiki/pulls) or give us a shout on shanghai(at)lewagon.com for suggestions!
### Acknowledgements
This original piece was written by Le Wagon alumni: [Adrien Pelegri (Batch #30)](https://github.com/apelegri) with the support of [Thibault Genaitay (Driver China)](https://github.com/tgenaitay) and [Stephane Delgado (Batch #61)](https://github.com/stephanedelgado).
### Contributors
- [Nathan Lee](https://github.com/kwnath)
- [Stephane Delgado](https://github.com/stephanedelgado)
## Summary
- [Registration process](#registration-process)
- [WeChat IDE](#wechat-ide)
- [What's this?](whats-this)
- [Quick tutorial](#quick-tutorial)
- [Project creation](#project-creation)
- [Dig into the "quickstart" project](#dig-into-the-quickstart-project)
- [Root directory](#root-directory)
- [Quickstart project pages](#quickstart-project-pages)
- [Take-away from the "quickstart" project](#take-away-from-the-quickstart-project)
- [The life cycle of your MP](#the-life-cycle-of-your-mp)
- [Application life cycle](#application-life-cycle)
- [Page life cycle](#page-life-cycle)
- [App life cycle affects page life cycle](#app-life-cycle-affects-page-life-cycle)
- [Core setup of your MP](#core-setup-of-your-mp)
- [Routing](#routing)
- [TabBar](#tabbar)
- [Window](#window)
- [Application orientation](#application-orientation)
- [Enable pull down refresh](#enable-pull-down-refresh)
- [Navbar, dynamic title](#navbar-dynamic-title)
- [Network timeout](#network-timeout)
- [Debug](#debug)
- [Create dynamic pages](#create-dynamic-pages)
- [WXML - HTML, what's the deal?](#wxml---html-whats-the-deal)
- [Data binding](#data-binding)
- [List loop rendering: wx:for](#list-loop-rendering-wxfor)
- [Conditional rendering: wx:if, wx:elif, wx:else](#conditional-rendering-wxif-wxelif-wxelse)
- [Template](#template)
- [Import a template](#import-a-template)
- [Define a template](#define-a-template)
- [Events](#events)
- [Event handler](#event-handler)
- [Event binding](#event-binding)
- [Event types classification](#event-types-classification)
- [Mini-program sharing](#mini-program-sharing)
- [Enable the forward button of the drop-down menu](#enable-the-forward-button-of-the-drop-down-menu)
- [Create a forward button within the current page](#create-a-forward-button-within-the-current-page)
- [WeChat design guidelines](#wechat-design-guidelines)
- [WeUI, basic front-end library ](#weui-basic-front-end-library)
- [WXSS](#wxss)
- [Style import](#style-import)
- [Selectors supported](#selectors-supported)
- [Built-in components](#built-in-components)
- [Navigator](#navigator)
- [Picker](#picker)
- [Switch](#switch)
- [Toast](#toast)
- [Modal](#modal)
- [Map](#map)
- [Leancloud DB](#leancloud-db)
- [1. Create a form](#1-create-a-form)
- [2. Install and initialize Leancloud](#2-install-and-initialize-leancloud)
- [3. Create an object and encapsulate data](#3-create-an-object-and-encapsulate-data)
- [4. Leancloud dashboard](#4-leancloud-dashboard)
- [5. Fetch data from Leancloud](#5-fetch-data-from-leancloud)
- [Recommendations](#recommendations)
- [Production: domain name whitelist](#production-domain-name-whitelist)
- [WeChat API](#wechat-api)
- [Get user information](#get-user-information)
- [Data cache](#data-cache)
- [Open the QR code scanner](#open-the-qr-code-scanner)
- [Location-based services](#location-based-services)
- [Image](#image)
- [FAQ](#faq)
___
## Registration process
The registration process is really tough, especially if you don’t have any experience with the fantastic Chinese administrative world.
The WeChat verification process will be long. Keep your calm.
From the WeChat mini-program registration, until the development release, you basically need to go through these steps:
- [Create an account](https://mp.weixin.qq.com) on WeChat back-end.
- **Pick the right type of application** and go through the registration process.
- Complete the **mini-program certification** process.
- Fill in your mini-program information.
Here is a list of materials you will need to register a mini-program as a company:
* Email, to create your Wechat account.
* Chinese ID. This person will own the account and scan QR codes a lot.
* Phone number, to certify your identity during the verification process.
* Chinese business license, to register as an enterprise.
* Company documents: organisation code, certificate and enterprise bank account.
* Fill in the official letter Tencent provides, sign it (by the admin) and stamp it with the enterprise stamp. Upload it.
We recommend you follow this comprehensive English manual on how to register and create a mini-program project: [Medium article](https://medium.com/@yelin.qiu/a-complete-manual-on-wechat-mini-program-development-8fd28a85ee0d)
or check this [official WeChat documentation](http://open.wechat.com/cgi-bin/newreadtemplate?t=overseas_open/docs/mini-programs/introduction/access-guide#introduction_access-guide) (Last Updated: 08/02/2017).
___
## WeChat IDE
#### What's this?
An [IDE](https://mp.weixin.qq.com/debug/wxadoc/introduction/index.html?t=201758) (integrated development environment) is a set of programming tools for writing an application. It consists of a code editor, a compiler and a debugger, accessible through a single graphical user interface.
Download the WeChat IDE here:
[Mac](https://servicewechat.com/wxa-dev-logic/download_redirect?type=darwin&from=mpwiki), [Windows 64](https://servicewechat.com/wxa-dev-logic/download_redirect?type=x64&from=mpwiki), [Windows 32](https://servicewechat.com/wxa-dev-logic/download_redirect?type=ia32&from=mpwiki)
#### Quick tutorial
Here is a quick tutorial to master the WeChat IDE and take the most from it.
A **Code editor** with the tree of your files on the side and a **Simulator** on the left, which displays the preview of your app.

Here is a complete list of buttons to perform tasks when you are in development:

**1. Profile:** click on it to log out from the IDE.
**2. Code Editing**
**3. Debug / Inspect:** see below.
**4. Project information:** see below.
**5. Compiler:** Can be usefull to compile the app when the auto-refresh of the view is not working.

**6. Scene value**
**7. Cache**
**8. Shut down:** Quit the project you are on and move toward another one.
**9. Hide the simulator**
**10. Devices:** It gives a list of devices to test mini-program responsivness.
**11. You can work on:** wifi, 4G, 3G, 2G.
**12. Hide arborescence**
**13. Manage your files:** Search, add and delete a folder or a file.
**Debugger / Inspector:**
This tool is an important part of the IDE, it looks like the good old *Chrome DevTools*.

**1. Top bar**
**Network:** This panel is to debug request and socket issues or page load performance.
**Storage:** allows to access all the data you have in your cache.
**AppData:** is used to display the current project data. You can directly edit the data in the panel and preview it.
**Wxml:** let you inspect and edit on the fly every elements of your page.
**Sensor:** you can simulate location and the performance of the mobile device to debug gravity sensing.
**2. Sources panel**
Sources panel displays the current project script files.
**3. Console**
The console will let you know what errors you have in your code by logging diagnostic information and interact with javascript in the page as your **console.log()** you have placed and more.
**Project information:**
This page is where you will find the current project details as your AppID, directory information and more. By clicking on the **preview option** you will be able to test the mini-program directly on your phone after scanning a QR code.
**Note:**
While you are testing your mini-program on your phone, you can enable the debugger tool directly on your device.

#### Project creation

___
## Dig into the "quickstart" project
This section will introduce the structure of the **"quickstart" provided by WeChat** (boilerplate) and the fundamentals you need to comply with this framework.
Download WeChat [quickstart.zip](assets/quickstart.zip).
**Quickstart arborescence:**
The index page of this boilerplate displays a welcome page with the current user profile's information. A click on your avatar will redirect to a new page displaying your current mini-program logs.
### Root directory
WeChat mini-programs start with **"app" files** (see the screenshot below). These files are the mini-program root directory therefore the entrance of your mini-program. (Here is the official [WeChat documentation](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/structure.html )).

**app.js** is the script code, the global logic of your mini-program. You can setup and manipulate the [life cycle functions](#application-life-cycle) of your MP, declare global variables or call an API.
**`Code snippet of the "app.js" file.`**
```javascript
// app.js
App({
onLaunch: function () {
// API call to get data from the local cache
var logs = wx.getStorageSync('logs') || []
logs.unshift(Date.now())
wx.setStorageSync('logs', logs)
},
// Get user information
getUserInfo:function(cb){
var that = this
if(this.globalData.userInfo){
typeof cb == "function" && cb(this.globalData.userInfo)
}else{
// Call login interface
wx.login({
success: function () {
wx.getUserInfo({
success: function (res) {
that.globalData.userInfo = res.userInfo
typeof cb == "function" && cb(that.globalData.userInfo)
}
})
}
})
}
},
// Global variable
globalData:{
userInfo:null
}
})
```
**app.json** is the global configuration of the overall mini-program. You can configure, MP (mini-program) page’s path, the MP window style, set the network timeout and debug configuration.
**`Code snippet of the "app.json" file.`**
```javascript
{
"pages":[
"pages/index/index",
"pages/logs/logs"
],
"window":{
"backgroundTextStyle":"gray",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "Hello World",
"navigationBarTextStyle":"black"
}
}
```
**Note:** Comments are not allowed in the **app.json** file.
**app.wxss** is the global style sheet of the mini-program. You should declare common style rules here.
### WeChat "quickstart" pages
The **two pages** of WeChat quickstart are:
- **index page** which is the welcome page.
- **logs page** which displays current user mini-program logs.
**Pages** folder is where you have or create your mini-program pages. Each page you create is **required to contain two files:**
- **.js** file for the logic of your interface.
- **.wxml** file for the interface layout.
You can add two more files in each page you create:
- **.json** file for page configuration.
- **.wxss** file for the style sheet of your interface.
**Rule:**
Each page of your mini-program can be composed of four different file extensions (js ; json ; wxml ; wxss) but **should have the same name.**
**Further details:**
A new page will always contain a **.js** file and a **.wxml** file minimum. The **.json** file extension is used just in case you want to override the [window configuration](#window) in this particular page. Add **.wxss** if you want to add a style sheet to your page.
Let's see what happens in each page of the quickstart project.
**`Code snippet of the "index.js" file.`**
```javascript
// index.js
// Get application instance
var app = getApp()
Page({
data: {
motto: 'Hello World',
userInfo: {}
},
// Event that redirect user to logs page
Tapped: function() {
console.log("tapped");
wx.navigateTo({
url: '../logs/logs'
})
},
onLoad: function () {
console.log('onLoad')
var that = this
// Call the application instance to get data
app.getUserInfo(function(userInfo){
// Updates userInfo data
that.setData({
userInfo:userInfo
})
})
}
})
```
**Snippet comments:**
1. The snippet above assigns the **app instance** to a variable. This app instance will be called in `Page()`function later on to collect user information.
2. Next it registers a `Page()` function and sets `data:` to dynamically bind data into the view.
3. `Tapped`function redirects the current user to his logs page.
4. `onLoad` function gets user information and updates `userinfo` data.
**`Code snippet of the "logs.js" file.`**
```javascript
// logs.js
var util = require('../../utils/util.js')
Page({
data: {
logs: []
},
onLoad: function () {
console.log(wx.getStorageSync('logs'))
this.setData({
logs: (wx.getStorageSync('logs') || []).map(function (log) {
return util.formatTime(new Date(log))
})
})
}
})
```
**Snippet comments:**
1. First it requires **util.js** in the purpose of calling `formatTime` later on.
2. It registers `Page()` function and sets `data:`.
3. `onLoad` function **retrieves current user logs** from the cache `wx.getStorageSync('logs')`. Then render logs in `formatTime` which is provided by the require of **util.js**.
**`Code snippet of the "utils.js" file.`**
```javascript
function formatTime(date) {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}
module.exports = {
formatTime: formatTime
}
```
**Note:**
In Utils are stored **imported libraries** that you may require elsewhere (in our example, util.js is required in log.js). In the code snippet above, the `formatTime` function is defined in **util.js** to properly display the date of your logs.
### Take-away from the "quickstart" project
Up to now you catch the fact that you will have **two layers in each page:**
- **Logical layer (.js):** process the data and send it to the view layer, while receiving events triggered from the view layer.
- **View layer (.wxml/.wxss):** display the data processed by the logical layer into a view, while sending the events of the view layer to the logical layer.

___
## The life cycle of your MP
We can break-down a mini-program life cycle in two cycles, the application cycle and the page cycle.
The **`App()`** life cycle is the **start & end point** of the mini-program whereas **`Page()`** life cycle is activated when users browse through the mini-program.
### Application life cycle
`App()` function is used to register a mini-program. It takes an object as parameter which specifies the life cycle functions of a MP.

**Comments:**
1. A user opens the mini-program which triggers **`onLaunch`** function and initialize the MP.
2. When the initialization is completed, the **`onShow`** function is triggered.
3. The **`onHide`** function is triggered when the current user exits the mini-program.
**`Code snippet of the "App()" life cycle functions.`**
```javascript
App({
onLaunch: function() {
// Do something when launch.
},
onShow: function() {
// Do something when show.
},
onHide: function() {
// Do something when hide.
},
onError: function(msg) {
console.log(msg)
},
globalData: 'I am global data'
})
```
WeChat framework offers a global function called `getApp()` which is an instance of `App()`.
**`Code snippet "getApp()" function.`**
```javascript
// .js
var appInstance = getApp()
console.log(appInstance.globalData) // I am global data
```
`getApp()` function, can be useful for the simple reason that you can’t define the `App()` function inside of a `Page()` function. In order to access the app instance you must call `getApp()` function.
### Page life cycle
`Page()` function is used to register a page. It accepts an object as a parameter, that specifies the initial data for the page, life cycle functions, event handler and so on.

**Comments:**
1. After page registration, the framework calls the **`onLoad`** function.
2. When a page loads, it calls the **`onShow`** function.
3. The first time the page is displayed, **`onShow`** function calls **`onReady`** to render the view.
4. On subsequent times, **`onShow`** function directly renders a view.
5. The **`onHide`** is triggered when the mini-program jumps to another page.
6. **`onUnload`** function is called when you quit a page by using `wx.redirectTo()`and `wx.navigateBack()`. Or when the current page is relaunched, `wx.reLaunch`.
**`Code snippet of "Page()" life cycle functions.`**
```javascript
Page({
data: {
text: "This is page data."
},
onLoad: function(options) {
// Do some initializations when page load.
},
onReady: function() {
// Do something when page ready.
},
onShow: function() {
// Do something when page show.
},
onHide: function() {
// Do something when page hide.
},
onUnload: function() {
// Do something when page close.
},
// Event handler
viewTap: function() {
this.setData({
text: 'Set some data.'
})
}
})
```
### App life cycle affects page life cycle

When the **`App()`** life cycle is complete, the page loads by calling **`onLoad`** for the first time, and will only call it once.
When the mini-program is running from the background (app life cycle) to the foreground (page life cycle), it first calls the **`App()`** `onShow` function and then calls the **`Page()`** `onShow` function when switching to the foreground.
**WeChat recommendations:**
- `App()` function cannot be reused and should be register once in the **app.js**.
- Do not call `onLaunch` when the `getCurrentPages()` page is not yet generated.
- By using `getApp()`you can obtain an **instance of App()** but lifecycle functions don’t attempt to call the `App()` functions.
___
## Core setup of your MP
The setup of your mini-program is simple and designed to save you time and frustration when having customization needs.
WeChat divides the **app.json configuration** in five parts:
- Routing
- TabBar
- Window
- Network timeout
- Debug
In this part we will **break-down** this complete **app.json setup** exemple.
**`Code snippet "app.json complete setup" example`**
```javascript
{
"pages":[
"pages/index/index",
"pages/form/form",
"pages/wagon/wagon",
],
"window":{
"navigationBarBackgroundColor": "#D03232",
"navigationBarTextStyle": "white",
"navigationBarTitleText": "Le Wagon",
"backgroundColor": "#eeeeee",
"backgroundTextStyle": "light",
"enablePullDownRefresh": true
},
"tabBar": {
"backgroundColor": "#FFFFFE",
"borderStyle": "#D3D3D3",
"selectedColor": "#D03232",
"color": "#131313",
"list": [{
"pagePath": "pages/index/index",
"iconPath": "image/form.png",
"selectedIconPath": "image/form-hover.png",
"text": "Form"
}, {
"pagePath": "pages/wagon/wagon",
"iconPath": "image/about.png",
"selectedIconPath": "image/about-hover.png",
"text": "About"
}]
}
}
```
### Routing
`pages` role in **app.json** is to **define all routes** of your mini-program. This item's configuration is **mandatory** and it **takes an array of strings**. Each sub-folder and files within the parent pages folder corresponds to a **routing path**.
**`Code snippet of the "app.json" file. `**
```javascript
{
"pages":[
"pages/index/index",
"pages/form/form",
"pages/wagon/wagon"
]
}
```
**Tip:**
Each time you **add a route path** to `"pages"`, the IDE will **automatically create** the folder and files that corresponds to the path you just created.
**The WeChat framework brings several routing logics:**

**Routing mode description:**
- **Initialization:**
Once the mini-program is launched, the first page is loaded by `onLoad` and `onShow` function.
- **Open a new page:**
Opening a new page hides the current page and jumps to another one using the `wx.navigateTo`.
Behind the scene the first page will be hidden by the call of the **onHide** function and jump over the other page by calling **onLoad** and **onShow**.

- **Page redirection:**
Close the current page by calling **onUnload** and jumps to a page within the app using `wx.redirectTo` which call **onLoad** and **onShow** functions.
- **Page return:**
`onUnload` the current page, calls `onLoad` function and then displays the target page by calling `onShow`.
- **Reloading,** `wx.reLaunch`:
Close all pages and reloads the current page. **Does not work on certain andriod devices.*
- **Switch tabs,** `wx.switchTab`: Jumps from one tabBar page to another one and close or hides all other non-tabBar pages by using **onUnload, onHide and onShow**. Discover all possible [scenarios for tabs switching](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/app-service/route.html).
**Switch tabs, navigation restrictions:**
* No callback at the top of the page.
* The tabBar path cannot take parameters.
**WeChat recommendations:**
- `navigateTo`, `redirectTo` can only open a non-tabBar page.
-`switchTab` can only open and display tabBar page.
-`reLaunch` can be used for every pages.
- The tabBar at the bottom of the page is displayed **according to the page you are on.** As long as the page you are on is defined in the tabBar, the tabBar will be display.
- **Page stack modification** will lead to routing and page status error, it is not recommended. Dig further in [pages stack mecanism](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/app-service/route.html).
**`getCurrentPages()`**:
This function is used to **get the instance of the current page stack.** It is given as an array in the page stack order. The first item of the array is the first page and the last item the current page.
### TabBar
`tabBar` as the name suggests, is the item which configures the top or bottom tab bar. **`tabBar` is an array** which accomodates a minimum of 2 and **a maximum of 5 tabs.**
**`Code snippet of the "app.json" file.`**
```javascript
{
"tabBar": {
"backgroundColor": "#FFFFFE",
"borderStyle": "#D3D3D3",
"selectedColor": "#D03232",
"color": "#131313",
"list": [{
"pagePath": "pages/index/index",
"iconPath": "image/form.png",
"selectedIconPath": "image/form-hover.png",
"text": "Form"
}, {
"pagePath": "pages/wagon/wagon",
"iconPath": "image/about.png",
"selectedIconPath": "image/about-hover.png",
"text": "About"
}]
}
}
```
**Attributes indication:**

Using the `tabBar` `list` key, requires an object in each element of the array.
**`List` attributes values are as follow:**

**TabBar attributes description:**

**WeChat recommendations:**
- Setting your `tabBar` position to top could not display icons.
- The limit size of your icons in the bottom `tabBar` are, 40kb, 81px\*81px.
### Window
The window item is used to set mini-program title and common window style.
**`Code snippet of the "app.json" file.`**
```javascript
"window": {
"navigationBarBackgroundColor": "#D03232",
"navigationBarTextStyle": "white",
"navigationBarTitleText": "Le Wagon",
"backgroundColor": "#eeeeee",
"backgroundTextStyle": "light",
"enablePullDownRefresh": true,
}
```
**Window attributes description:**
| Attribute | Type | Default value | Description |
| --------- | ---- | ------------- | ----------- |
| navigationBarBackgroundColor | HexColor | `#000000` | Navigation bar background color |
| navigationBarTextStyle | String | `white` | Navigation bar title color, `black` or `white` |
| navigationBarTitleText | String | | Navigation bar title |
| navigationStyle | String | `default` | Navigation bar style, `default` or `custom`. Use `custom` to customize the navigation bar style. |
| backgroundColor | HexColor | `#ffffff` | Application background color. Ex: background color you see on pull to refresh, does not affect the color of the `` elements. |
| backgroundTextStyle | String | `dark` | Pull to refresh text style, `dark` or `light` |
| backgroundColorTop | String | `#ffffff` | Background color of the top part of the window. Only supported on iOS |
| backgroundColorBottom | String | `#ffffff` | Background color of the bottom part of the window. Only supported on iOS |
| enablePullDownRefresh | Boolean | `false` | Enable or disable pull to refresh app-wide. |
| onReachBottomDistance | Number | `50` | Set the distance from the bottom of the page at which the `onReachBottom()` callback should be triggered. |
| pageOrientation | String | `portrait` | Set screen rotation support. Supports `auto`, `portrait` and `landscape`. |
#### Application orientation
The application default orientation can be configured using `pageOrientation` in `window` in the `app.json` configuration file. This attributes supports 3 values:
- Set to `auto` to allow the mini program to work in both Portrait and Landscape modes.
- Set to `portrait` to force the mini program to display only in portrait mode
- Set to `landscape` to force the mini program to display only in landscape mode
#### Enable pull down refresh
`"enablePullDownRefresh": true` needs to be configured in the global **app.json** as above and then you can call `onPullDownRefresh()` in mini-program pages.
**`Code snippet of the "Enable pull down refresh in a page" file.`**
```javascript
// .js
Page({
// Pull down the trigger event
onPullDownRefresh() {
// Stop the dropdown refresh
wx.stopPullDownRefresh()
}
})
```
#### Navbar dynamic title
WeChat offers the possibility to **change the title** of the top **navigation bar** within each page.
**`Code snippet of the "change navbar title" file.`**
```javascript
// .js
Page({
// Loading spinner when page loads
onload: function (){
wx.showNavigationBarLoading()
},
// Change navigation bar title
onShow: function () {
wx.setNavigationBarTitle({
title: 'My new navabar title',
success: function(res){
console.log(res)
}
})
}
})
```
### Network timeout
Network timeout may be provided in a variety of network requests.
Here is the link to the [WeChat documentation](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/config.html ) if you want to go further.
### Debug
Here is a link to the [WeChat documentation](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/config.html).
___
## Create dynamic pages
### WXML - HTML, what's the deal?
**WXML** is a WeChat markup language similar to HTML. It combines a **basic library of components** and **an event system** to build dynamic pages.
The WeChat event system behaves like classic Javascript events which **handle logical responses to the view layer.**
The table below lists the **significant differences** you will face in development between **WXML / HTML:**

**Further explanations about ``**:
`` is **not a component**, it is only a **packaging element**, it will not do any rendering in the page and **only accept control properties**.
**Note:** All components and attributes are lowercase.
### Data binding
The Mini-program framework does not allow developers to use the DOM to control your WXML elements. Instead, you will **update your view layer** (.wxml file) **via data binding method:**

In order to comply with WeChat requirements the `data` attribute has to be initialized **in JSON format** within `Page()` function. **Data binding** technique allows to **update data dynamically** within the view layer.
A good practice is to initialize `data` at the top of the `Page()` function.
**`Code snippet "data binding" example.`**
```html
{{text}}{{array[0].msg}}
```
```javascript
// .js
Page({
data: {
text: 'init data',
array: [{msg: '1'}, {msg: '2'}]
}
}
```
The dynamic `data:` which is passed over to the view layer is taken from the data attributes in the corresponding `Page()` function.
**Data binding syntax:**
Data binding uses [Mustache syntax](https://mustache.github.io/mustache.5.html) (double braces) to **wrap variables.** This syntax is a logic less template engine analysis. In short, it is very convenient and easy to use!
WeChat offers lot of possibilities regarding [data binding usage](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/view/wxml/data.html ). You have the oportunity to use data binding on component attributes, properties, string operations, arithmetic operations, data path and array.
### List loop rendering: wx:for
The `wx:for` control property binds an array from your logical layer (.js file), loops through it and assigns the data.
**`Code snippet "wx:for" example.`**
```html
{{index}}: {{item.message}}
```
```javascript
// .js
Page({
data: {
array: [{
message: 'foo'
}, {
message: 'bar'
}]
}
})
```
Similar to `` you can use **``** to render **multiple lines** block. (See [block](#wxml---html-whats-the-deal) in the WXML table above).
**`Code snippet "block wx:for" example.`**
```html
```
For more details on the code above see this [Github repository](https://github.com/apelegri/wagonform-wechat-mp/tree/master/pages/form).
**Further resources:**
- For more details about list rendering refer to [WeChat documentation ](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/view/wxml/list.html ).
### Conditional rendering: wx:if, wx:elif, wx:else
Similar to `wx:for`, **`wx:if`** is used to define a conditional statement and determine whether the block should be rendered or not.
**`Code snippet "wx:if" example.`**
```html
1 2 3
```
```javascript
// .js
Page({
data: {
length: 10
}
})
```
If you want to display **more than one tag** within your **conditional statement block** you can use **``**.
```html
view1 view2
```
Dig further in `wx:if` [WeChat documentation](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/view/wxml/conditional.html).
### Template
Templates allow to define code snippets you want to reuse several times in different files of your mini-program.
WXML template item has its own scope and can only use data to pass in.
#### Define a template
First, to declare a template you need to define its name.
**`Code snippet "template" example. `**
```html
{{index}}: {{msg}} Time: {{time}}
```
Later on if you want to call a template within the same file use the **`is` attribute** and the **template name as a value** to declare the required template. And don't forget to pass data to the template using the `data` attribute.
```javascript
// .js
Page({
data: {
item: {
index: 0,
msg: 'this is a template',
time: '2017-05-18'
}
}
})
```
#### Import a template
To declare a template already defined in a new file you first need to import it.
**`Code snippet "define a template in a specific file" exemple`**
```html
{{text}}
```
**`Code snippet "import and call the template in index.wxml" exemple`**
```html
```
More details on the WeChat documentation [here](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/view/wxml/template.html).
### Events
#### Event handler
In addition to data initialization and life cycle functions, the framework allows to define **event handling functions.**
WXML element (event handler) triggers the event and the **logical layer binds the event handler** to receive an event object as a parameter.
**`Code snippet "event handler" example.`**
```html
```
```javascript
// .js
Page({
data: {
count: 1
},
add: function(e) {
this.setData({
count: this.data.count + 1
})
}
})
```
**`setData()` :**
This function **updates data** within the logical layer which next will be send to the view layer.
`setData()` function receives an object as a parameter and updates the key value by using `this.data` as a **data path.**
#### Event binding
There are many kind of binding events, most components have their own definition of binding event.
**Components binding events:**
- **`bindsubmit`** for a fom.
- **`bindinput`** for an input.
- **`bindscroll`** for a scroll-view.
**`Code snippet "form binding event" example.`**
```html
```
```javascript
// form.js
// Form submission function
Page({
bindFormSubmit: function(e) {
// Treatment
}
})
```
**Classic binding events:**
- **`bind+event_type`**
- **`catch+event_type`**
**`Code snippet "data binding illustration" example.`**
```html