原创声明:本文为作者原创,未经允许不得转载,经授权转载需注明作者和出处
分享一个小程序Markdown和HTML解析库,支持Wepy。
Towxml 是一个可将HTML
、Markdown
转为微信小程序WXML
(WeiXin Markup Language)的渲染库。
用于解决在微信小程序中Markdown
、HTML
不能直接渲染的问题。
以下截图即demo
目录编译的效果
1. 克隆TOWXML到小程序根目录
git clone https://github.com/sbfkcel/towxml.git
2. 在小程序app.js
中引入库
//app.js
const Towxml = require('/towxml/main'); //引入towxml库
App({
onLaunch: function () {
},
towxml:new Towxml() //创建towxml对象,供小程序页面使用
})
3. 在小程序页面文件中引入模版
<!--pages/index.wxml-->
<!--引入towxml模版入口文件,并使用模版-->
<import src="/towxml/entry.wxml"/>
<template is="entry" data="{{...article}}"/>
4. 在小程序对应的js中请求数据
//pages/index.js
const app = getApp();
Page({
data: {
//article将用来存储towxml数据
article:{}
},
onLoad: function () {
const _ts = this;
//请求markdown文件,并转换为内容
wx.request({
url: 'http://xxx/doc.md',
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: (res) => {
//将markdown内容转换为towxml数据
let data = app.towxml.toJson(res.data,'markdown');
//设置文档显示主题,默认'light'
data.theme = 'dark';
//设置数据
_ts.setData({
article: data
});
}
});
}
})
5. 引入对应的WXSS
/**pages/index.wxss**/
/**基础风格样式**/
@import '/towxml/style/main.wxss';
/**如果页面有动态主题切换,则需要将使用到的样式全部引入**/
/**主题配色(浅色样式)**/
@import '/towxml/style/theme/light.wxss';
/**主题配色(深色样式)**/
@import '/towxml/style/theme/dark.wxss';
OK,大功告成~~
如果为了追求极致的体验,建议将markdown
、html
转换为towxml数据的过程放在服务器上,在小程序中直接请求数据即可。
1. 依赖环境
需要 Node.js 环境。(已经安装请忽略)
2. 安装towxml
npm install towxml
3. 接口使用
const Towxml = require('towxml');
const towxml = new Towxml();
//Markdown转WXML
let wxml = towxml.md2wxml('# Article title');
//html转WXML
let wxml = towxml.html2wxml('<h1>Article title</h1>');
//Markdown转towxml数据
let data = towxml.toJson('# Article title','markdown');
//htm转towxml数据
let data = towxml.toJson('# Article title');
towxml/demo
添加为小程序工程towxml
到demo
目录MIT