描述下小程序富文本解决方案
使用插件 Parser富文本插件
点git: https://github.com/jin-yufeng/Parser
最近公司在开发微信小程序,一些资讯的详情内容是HTML富文本格式的的,但是微信小程序不能直接解析HTML,需要将内容中的HTML标签转换成微信小程序所支持的标签。
因为cml 官网的rich-text : 组件并不支持 HTML 标签格式,
cml rich-text: https://cmljs.org/components/richtext.html
为了弥补这一不足, 寻找网络
后来找到了一个很好用的插件:Parser。
今天分享给大家,插件Github地址:https://github.com/jin-yufeng/Parser
demo地址: https://github.com/dL-hx/cml-wx-richtext-demo
使用Parser解析富文本数据
1.将下载下来的插件文件夹复制到我们的项目根目录下(其中emojis文件可根据自己所需决定要或者不要,其他的文件必须要)
复制下方的文件
m-rich-text.interface
<script cml-type="interface">
/*
.interface 描述 组件的输入和输出。
定义一个inteface用于描述组件的属性和事件
1、 如何区分组件属性和事件?
通过类型来区分,事件为函数类型,属性为非函数类型
2、 如何定义组件属性
给interface添加同名的属性即可,指定类型
3、 如何定义组件事件
以事件名称为key值给interface定义属性,该属性是一个函数类型,返回值为void,
定义函数的第一个参数为自定义事件传递的detail对象类型
*/
interface MRichTextInterface {
nodes: String,
}
</script>
m-rich-text.wx.cml
<template>
<view class="contain">
<!--
在需要使用页面的 wxml 文件中添加
-->
<parser html="{{nodes}}" tag-style="{{tagStyle}}"></parser>
</view>
</template>
<script>
class MRichText implements MRichTextInterface {
props = {
nodes: {
type: String,
default: ''
}
}
data = {
tagStyle:{
img:"width:100%!important;"
}
}
computed = {
}
watch = {
}
methods = {
}
beforeCreate() {
}
created() {
}
beforeMount() {
}
mounted() {
}
beforeDestroy() {
}
destroyed() {
}
}
export default new MRichText();
</script>
<style scoped>
.contain{
padding: 30cpx;
font-size: 28cpx;
}
</style>
<script cml-type="json">
{
"base": {
"component": true,
"usingComponents": {
"parser":"./parser/parser"
}
}
}
</script>
2.在需要使用该插件的(.json文件)中引入Parse模块
{
"base": {
"component": true,
"usingComponents": {
"parser":"./parser/parser"
}
}
}
3.在需要是用的m-rich-text中引入m-rich-text.cml(注意文件路径)
"base": {
"usingComponents": {
"m-rich-text": "../../components/m-rich-text/m-rich-text"
}
},
4.进行数据绑定
页面层 Detail.cml
src\pages\detail\detail.cml
<template>
<view class="article">
<text class="article-title">{{ title }}</text>
<view class="article-content">
<m-rich-text nodes="{{ content }}"> </m-rich-text>
</view>
</view>
</template>
<script>
import cml from 'chameleon-api'
import newsData from '../../assets/json/news.json'
class Detail {
data = {
// title:'资讯标题',
title:newsData.data.title,
// content:'<div>我是HTML代码</div>',
content:newsData.data.content,
}
computed = {
}
watch = {
}
methods = {
}
beforeCreate(query) {
}
created(query) {
}
beforeMount(query) {
}
onShow() {
}
mounted() {
}
onHide() {
}
beforeDestroy() {
}
destroyed() {
}
}
export default new Detail();
</script>
<style>
.article-title{
padding: 20cpx 30cpx;
font-size: 36cpx;
font-weight: bold;
line-height: 1.5;
text-align: center;
}
</style>
<script cml-type="json">
{
"base": {
"usingComponents": {
"m-rich-text": "../../components/m-rich-text/m-rich-text"
}
},
"wx": {
"navigationBarTitleText": "资讯详情",
"backgroundTextStyle": "dark",
"backgroundColor": "#E2E2E2"
}
}
</script>
完成后页面就能够正常渲染HTML富文本数据了
资讯展示