1、背景
在使用微信小程序开发AI程序的时候,AI大模型输出的是markdown格式的文本,而微信小程序是不支持markdown语法的,需要使用插件,这里使用的是towxml插件。
并且towxml插件不支持Latex数学公式和yuml图 ,需要自己搭建一个服务。
2、安装towxml
安装流程如下:
-
克隆项目到本地
git clone https://github.com/sbfkcel/towxml.git
国内地址:
git clone gitee.com/tuyuan/towx…
-
安装构建依赖
npm install或yarn
-
编辑配置文件
towxml/config.js(可以先按照默认的) -
运行
npm run build或yarn run build即可 -
新构建出来的文件在
dist目录下,将dist目录复制到你的小程序项目中并将目录名称改为towxml即可
3、使用towxml
3.1 引入库
//app.js
App({
// 引入`towxml3.0`解析方法
towxml:require('/towxml/index')
})
3.2 在页面配置文件中引入towxml组件
{
"usingComponents": {
"towxml":"/towxml/towxml"
}
}
3.3 在页面中插入组件
<towxml nodes="{{markdownContent}}" />
3.4 解析内容
在对应的js文件中增加文本的处理,如下:
content就是带markdown标签的文本;markdownContent就是转化后的文本。
let markdownContent = app.towxml(content, "markdown")
...
this.setData({
markdownContent
})
app.towxml(str,type,options)有三个参数
str必选,html或markdown字符串type必选,需要解析的内容类型html或markdownoptions[object] 可选,可以该选项设置主题、绑定事件、设置base等base[string] 可选,用于指定静态相对资源的base路径。例如:https://xx.com/static/theme[string] 可选,默认:light,用于指定主题'light'或'dark',或其它自定义events[object] 可选,用于为元素绑定事件。key为事件名称,value则必须为一个函数。例如:{tap:e=>{console.log(e)}}
4、安装markdown-server让towxml支持LaTex和yuml
towxml是不支持Latex数学公式和yuml图的显示,需要自己搭建一个解析服务。
解析服务markdown-server代码地址:
-
下载代码
-
安装依赖
npm install 或 yarn -
启动服务
node index.js -
查看服务
启动后会默认启动一个端口是8001 的服务(编辑 index.js 最后一行的端口号即可改变端口),通过如下链接可以测试服务是否正常启动?是否能够正常解析Latex和yuml流程图:
(本地)LaTeX 数学公式
http://localhost:8001/?tex=x%20%3D%20%7B-b%20%5Cpm%20%5Csqrt%7Bb%5E2-4ac%7D%20%5Cover%202a%7D.
(本地)yuml 流程图
- 发布到服务器
发布到公网服务器上后,在NGINX中做一下映射:
server {
listen 80;
server_name markdown.****.tech; ## 重要!!!修改成你的外网域名
location / { ## 前端项目
proxy_pass http://localhost:8001/;
}
}
-
修改微信小程序中的towxml/config.js 配置,把解析的api改成自己的解析服务的域名
latex:{ api:'http://markdown.****.tech/?tex' }, // yuml图解析APPI yuml:{ api:'http://markdown.****.tech/?yuml' },
这是towxml的基础应用,后续会讲如何在AI流式回复中使用towxml,有兴趣可以加入学习群: