微信小程序中Towxml解析Markdown及html

一、Towxml

Towxml 是一个让小程序可以解析Markdown、HTML的解析库。
在这里插入图片描述

二、引入

2.1 clone代码

git clone https://github.com/sbfkcel/towxml.git

2.2 安装依赖

npm install

2.3 打包

npm run build

2.4 引入文件

将dist文件复制到微信小程序根目录,改名为towxml
在这里插入图片描述

三、使用

3.1 app.js引入

//app.js
App({
    // 引入`towxml`解析方法
    towxml:require('/towxml/index')
})

3.2 页面配置文件json中引用

{
  "usingComponents": {
    "towxml": "../towxml/towxml"
  }
}

3.3 页面js使用

const app = getApp();
Page({
    data: {
        content: ''
    },
    onLoad: function (options) {
        // todo 库中返回markdown
        const contentMd = '# 一级标题';
        let result = app.towxml(contentMd, 'markdown', {
        	theme: 'light'
        });
        this.setData({
            content: result
        });
    }
})

3.4 wxml展示

<towxml nodes="{{content}}"/>

3.5 效果

在这里插入图片描述
在这里插入图片描述

### 如何在 Wepy 项目中集成和使用 Towxml #### 修改 `index.wpy` 文件以支持 Towxml 渲染 为了使 Wepy 支持 Towxml,需先调整页面结构文件。假设已经在 `src/pages/index/index.wpy` 中定义了一个基础模板[^1]: ```html <template> <view> <text class="title">欢迎使用wepy</text> </view> </template> <script> export default class Index extends wepy.page { } </script> ``` #### 安装 Towxml 插件 接下来安装 Towxml npm 包以便于后续操作。打开命令行工具并执行如下指令完成插件下载: ```bash npm install towxml --save ``` #### 配置 Towxml 初始化设置 编辑项目的入口文件 `app.js` 或者创建一个新的配置文件用于初始化 Towxml 实例: ```javascript import { createApp } from 'towxml'; const app = getApp(); createApp(app); ``` 此段代码确保了当应用启动时会自动加载 Towxml 并将其挂载到全局对象上。 #### 更新页面逻辑处理部分 回到之前提到的 `index.wpy` 页面脚本区域, 添加必要的属性声明以及方法实现来调用 Towxml 功能: ```js <script> import wepy from '@wepy/core'; import towxml from 'towxml'; export default class Index extends wepy.page { data = { content: '<p>这是通过 Towxml 解析的内容。</p>' }; onLoad() { this.parseContent(this.data.content); } methods = { parseContent(htmlString){ const result = towxml.htmlToWXML(htmlString); console.log(result); // 将解析后的结果赋给data中的变量,从而渲染到界面上 this.$apply(() => { this.parsedResult = result; }); } }; } </script> ``` 上述代码展示了如何利用 Towxml 提供的方法将 HTML 字符串转换成适合微信小程序使用的 WXML 结构,并最终显示出来[^2]。 #### 调整页面展示内容 最后一步是在 `<template>` 标签内加入新的绑定表达式,让经过 Towxml 处理过的结果能够呈现在用户面前: ```html <template> <view> <!-- 原始文本 --> <text class="title">{{parsedResult}}</text> <!-- 如果需要直接插入复杂的HTML,则可以这样写 --> {{#raw}} {{{ parsedResult }}} {{/raw}} </view> </template> ``` 以上就是完整的在 Wepy 应用程序里集成了 Towxml 的过程说明。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员Meteor

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值