最近項目上遇到在微信小程序里需要顯示商品內容,商品內容是通過接口讀取的服務器中的富文本內容,是html格式的,小程序默認是不支持html格式的內容顯示的。
一、使用小程序的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}}"/>
這樣就可以在微信小程序中嵌入html內容了
========================================================================================================
二、使用rich-text組件
rich-text官方文檔連接鏈接: https://developers.weixin.qq.com/miniprogram/dev/component/rich-text.html.
1、在wxml使用標簽
<rich-text nodes="{{content}}"> </rich-text>