# WXS

WXS (WeiXinScript) is a script segment inlined in WXML. Through WXS, you can inline a small number of processing scripts in the template, enriching the data preprocessing capabilities of the template. In addition, WXS can be used to write simple [WXS event response functions.

WXS is syntactically similar to JavaScript with a few restrictions.For a complete understanding of WXS syntax, refer to WXS Syntax Reference .

Here are some simple examples of using WXS.

# Page rendering

<!--wxml-->
<wxs module="m1">
var msg = "hello world";

module.exports.message = msg;
</wxs>

<view> {{m1.message}} </view>

Page output:

hello world

# data processing

// page.js
Page({
  data: {
    array: [1, 2, 3, 4, 5, 1, 2, 3, 4]
  }
})
<!--wxml-->
<!-- 下面的 getMax 函数,接受一个数组,且返回数组中最大的元素的值 -->
<wxs module="m1">
var getMax = function(array) {
  var max = undefined;
  for (var i = 0; i < array.length; ++i) {
    max = max === undefined ?
      array[i] :
      (max >= array[i] ? max : array[i]);
  }
  return max;
}

module.exports.getMax = getMax;
</wxs>

<!-- 调用 wxs 里面的 getMax 函数,参数为 page.js 里面的 array -->
<view> {{m1.getMax(array)}} </view>

Page output:

5