最近在做需要展示文章详情的功能,详情打算用Markdown展示,发现微信小程序在支持Markdown方面不是很友好,小蛋我无意中发现一个好用的组件,Twoxml,完美支持Markdown,下面就带大家手把手实现Markdown功能
Twoxml 介绍
|Twoxml 官网 https://github.com/sbfkcel/towxml
Twoxml是一个可将HTML、Markdown转为微信小程序WXML的渲染库,支持以下功能:

image.png
使用Twoxml可以实现如下的Markdown效果

image.png
在小程序中引入Twoxml
构建Twoxml
- 克隆项目到本地
git clone https://github.com/sbfkcel/towxml.git
- 如果没有安装过npm依赖,先安装依赖
npm install 或 yarn
-
编辑配置文件twoxml/config.js
根据自己的实际需求保留你需要的功能即可
运行 **npm run build** 或 **yarn run build** 即可
> 构建好后出来的文件在dist目录下,将dist目录复制到小程序项目根目录中并将目录名称改为towxml即可使用

image.png
在小程序中使用Twoxml
上一步我们已经把twoxml文件夹引入到小程序中:

image.png
1. 引入库 /app.js
// app.js
App({
towxml:require('/towxml/index')
})
2. 在具体页面的配置文件中引入twoxml组件
{
"usingComponents": {
"towxml":"/towxml/towxml"
}
}
3. 在页面中插入组件
<view class="content-info">
<towxml nodes="{{article}}"/>
</view>
4. 在js中解析内容
//解析markdown数据
markdownto: function (content) {
let result = app.towxml(content,'markdown',{
base:'www.xxx.com', // 相对资源的base路径
theme:'light', // 主题,默认`light`
events:{ // 为元素绑定的事件方法
tap:(e)=>{
console.log('h4',e);
}
}
});
// 更新解析数据
this.setData({
article:result
});
},