微信小程序 使用wxParse解析html

首先去 https://github.com/icindy/wxParse 下载wxParse,只拷贝wxParse文件夹即可。

 

下面是具体的使用步骤:

1.在app.wxss全局样式文件中,需要引入wxParse的样式表

@import "/page/wxParse/wxParse.wxss";

2.在需要加载html内容的页面对应的js文件里引入wxParse

var WxParse = require('../../wxParse/wxParse.js');

3.通过调用WxParse.wxParse方法来设置html内容

 
/**
* WxParse.wxParse(bindName , type, data, target,imagePadding)
* 1.bindName绑定的数据名(必填)
* 2.type可以为html或者md(必填)
* 3.data为传入的具体数据(必填)
* 4.target为Page对象,一般为this(必填)
* 5.imagePadding为当图片自适应是左右的单一padding(默认为0,可选)
*/
 
Page({
  data: {
  },
  onLoad: function () {
    var that = this;
    wx.request({
        url: '', 
        method: 'POST',
        data: {
            'id':13
        },
        header: {
            'content-type': 'application/json'
        },
        success: function(res) {
            var article = res.data[0].post;
            WxParse.wxParse('article', 'html', article, that,5);
        }
    })
  }
})

4.在页面中引用模板

<import src="../../wxParse/wxParse.wxml"/>
<template is="wxParse" data="{{wxParseData:article.nodes}}"/>

 

wxParse多数据循环使用方法

方法介绍

/**
* WxParse.wxParseTemArray(temArrayName,bindNameReg,total,that)
* 1.temArrayName: 为你调用时的数组名称
* 3.bindNameReg为循环的共同体 如绑定为reply1,reply2...则bindNameReg = 'reply'
* 3.total为reply的个数
*/
var that = this;
WxParse.wxParseTemArray("replyTemArray",'reply', replyArr.length, that)

使用方式

  • 循环绑定数据
 var replyHtml0 = `<div style="margin-top:10px;height:50px;"><p class="reply"> wxParse回复0:不错,喜欢[03][04] </p> </div>`; 
var replyHtml1 = `<div style="margin-top:10px;height:50px;"> <p class="reply"> wxParse回复1:不错,喜欢[03][04] </p> </div>`; 
var replyHtml2 = `<div style="margin-top:10px;height:50px;"> <p class="reply"> wxParse回复2:不错,喜欢[05][07] </p> </div>`; 
var replyHtml3 = `<div style="margin-top:10px;height:50px;"> <p class="reply"> wxParse回复3:不错,喜欢[06][08] </p> </div>`; 
var replyHtml4 = `<div style="margin-top:10px; height:50px;"> <p class="reply"> wxParse回复4:不错,喜欢[09][08] </p> </div>`; 
var replyHtml5 = `<div style="margin-top:10px;height:50px;"> <p class="reply"> wxParse回复5:不错,喜欢[07][08] </p> </div>`; 

var replyArr = []; 
replyArr.push(replyHtml0); 
replyArr.push(replyHtml1); 
replyArr.push(replyHtml2); 
replyArr.push(replyHtml3); 
replyArr.push(replyHtml4); 
replyArr.push(replyHtml5); 
for (let i = 0; i < replyArr.length; i++) { 
    WxParse.wxParse('reply' + i, 'html', replyArr[i], that); 
    if (i === replyArr.length - 1) { 
        WxParse.wxParseTemArray("replyTemArray",'reply', replyArr.length, that) 
    } 
} 

  • 模版使用
   <block wx:for="{{replyTemArray}}" wx:key="">
        回复{{index}}:<template is="wxParse" data="{{wxParseData:item}}"/>
    </block>

 

示例:(直接上图)

1、.wxml文件:

引入wxParse.wxml:<import src=“../../wxParse/wxParse.wxml” />;

引用模板<template>....

2、js文件:

//引入文件
var WxParse = require('../../wxParse/wxParse.js');

 

posted @ 2018-04-08 18:46  十一是假期啊  阅读(7341)  评论(4编辑  收藏  举报