Towxml 是一个可将HTML
、Markdown
转为微信小程序WXML
(WeiXin Markup Language)的渲染库。javascript
用于解决在微信小程序中Markdown
、HTML
不能直接渲染的问题。css
如下截图即demo
目录编译的效果html
1. 克隆TOWXML到小程序根目录java
git clone https://github.com/sbfkcel/towxml.git
2. 在小程序app.js
中引入库node
//app.js const Towxml = require('/towxml/main'); //引入towxml库 App({ onLaunch: function () { }, towxml:new Towxml() //建立towxml对象,供小程序页面使用 })
3. 在小程序页面文件中引入模版git
<!--pages/index.wxml--> <!--引入towxml模版入口文件,并使用模版--> <import src="/towxml/entry.wxml"/> <template is="entry" data="{{...article}}"/>
4. 在小程序对应的js中请求数据github
//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. 引入对应的WXSSnpm
/**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