和我一起学习微信小程序(六),使用highlight实现代码高亮

 0 0条评论

highlight,做技术的大家应该都听说过,我之前的文章也有在网页里如何实现代码高亮。

页面代码高亮highlightjs的使用

因为我的网站里很多都是技术类文章,所以代码高亮是必须的,但是在小程序里如何实现呢?那就要费一番波折了,研究了好久才搞定。

首先,新建detail页面,把highlight.js复制进来,再把主题,我用的是vs2015复制进来,css后缀改成wxss,如图:


在detail.wxss中,引入

@import "../../vs2015.wxss";

在detail.js中,引入

import http from '../../utils/http'
import hljs from '../../utils/highlight'

由于我再后端生成的code都是html转义过的,所以要定义一个反转移方法,恢复成html代码

  escape2Html(str) {
    var arrEntities = {
      'lt': '<',
      'gt': '>',
      'nbsp': ' ',
      'amp': '&',
      'quot': '"'
    }
    return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) {
      return arrEntities[t]
    })
  },

接下去就是核心代码,主要的思路就是,通过正则把code标签内的内容提取出来,通过{hljs.highlightAuto(html).value方法,转换成highlight代码。如下:

getarticle(articleid) {
    http({
      url: `/article/full/${articleid}`
    }).then((res) => {
      const rPre = /<pre>[\s\S]*?<\/pre>/g
      const rCode = /<code.*?>([\s\S]*?)<\/code>/g
      //r.test(res.data.content)
      const that=this
      res.data.content=res.data.content.replace(rPre, function (word) {
        rCode.test(word)
        let html=that.escape2Html(RegExp.$1)
        return `<pre><code class=\"hljs\">${hljs.highlightAuto(html).value}</code></pre>`
      })
      this.setData({
        articleModel: res.data
      })
    }).catch((err) => {
      console.log('获取文章详情错误', err)
    })
  },

至此,小程序就可以支持代码高亮啦


好了,接下去就是详情页布局啦。

第七篇:和我一起学习微信小程序(七),详情页布局

本文作者:双黑

版权声明:本站文章欢迎链接分享,禁止全文转载!

游客