简介 小程序渲染markdown的内容,出现图片不居中,代码块样式失效,就算是安装了markdown的插件,显示出来的效果也不尽人意,在网上找了很多办法,无法解决问题,下面介绍一种办法,亲测有效。
1.引入文件
代码语言:javascript复制const parser = require('./wemark/parser');
注:文件引入的路径根据自己项目实际情况而定
2.调用
代码语言:javascript复制this.parsedData = parser.parse(html, {
link: false,
highlight: false
});
注:
① parsedData为data中定义的变量
② html为markdown的内容
3.页面渲染
代码语言:javascript复制<view class="wemark_wrapper">
<block wx:for="{{parsedData}}" wx:key="blockIndex" wx:for-index="blockIndex" wx:for-item="renderBlock">
<view class="wemark_block_{{renderBlock.type}}">
<block wx:if="{{renderBlock.isArray}}" wx:for="{{renderBlock.content}}" wx:key="inlineIndex" wx:for-index="inlineIndex" wx:for-item="renderInline">
<text class="wemark_inline_{{renderInline.type}}" wx:if="{{renderInline.type === 'text' || renderInline.type === 'code' || renderInline.type === 'strong' || renderInline.type === 'strong_em' || renderInline.type === 'deleted' || renderInline.type === 'em' || renderInline.type === 'table_th' || renderInline.type === 'table_td'}}">{{renderInline.content}}</text>
<!-- 代码高亮 -->
<text class="wemark_inline_code_{{renderInline.type}}" wx:if="{{renderInline.type&&renderBlock.highlight}}">{{renderInline.content}}</text>
<text class="wemark_inline_code_text" wx:if="{{!renderInline.type}}">{{renderInline}}</text>
<navigator class="wemark_inline_link" url="{{renderInline.data.href}}" wx:if="{{renderInline.type === 'link'}}">{{renderInline.content}}</navigator>
<image mode="widthFix" class="wemark_inline_image" src="{{renderInline.src}}" wx:if="{{renderInline.type === 'image'}}"></image>
</block>
<block wx:if="{{!renderBlock.isArray}}">
<view wx:if="{{renderBlock.type === 'code'}}">{{renderBlock.content}}</view>
<video wx:if="{{renderBlock.type == 'video'}}" class="wemark_block_video" src="{{renderBlock.src}}" poster="{{renderBlock.poster}}" controls></video>
<view wx:if="{{renderBlock.type === 'html'}}" v-html="renderBlock.content"></view>
</block>
</view>
</block>
</view>