You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Showdownjs将自定义标签渲染为自定义HTML块?

实现Showdown自定义代码块渲染的方法

Showdown支持通过**扩展(extensions)**来自定义渲染逻辑,这是实现你需求的核心方式。具体步骤如下:

  • 创建自定义扩展
    编写一个扩展,识别带有[custom-section]标记的代码块,替换成目标HTML结构:
    const customSectionExtension = {
      type: 'output',
      filter: function (html) {
        // 匹配带[custom-section]标记的代码块HTML
        const regex = /<pre><code>\[custom-section\]\n([\s\S]*?)<\/code><\/pre>/g;
        return html.replace(regex, function(match, content) {
          // 按换行分割内容为左右两部分
          const lines = content.trim().split('\n').map(line => line.trim());
          const leftContent = lines[0] || '';
          const rightContent = lines[1] || '';
          // 返回目标HTML结构
          return `
    
${leftContent}
${rightContent}
`.trim(); }); } }; ```
  • 注册并使用扩展
    初始化Showdown转换器时传入自定义扩展:

    const converter = new showdown.Converter({
      extensions: [customSectionExtension]
    });
    
  • 测试转换逻辑
    将目标Markdown传入转换器,即可得到期望的HTML:

    const markdown = `Some text here 
    
    
H1

H2

You can download the latest release tarball directly from [releases]

```[custom-section]
Text within left-aligned div
Text within right-aligned div
````;

const html = converter.makeHtml(markdown);
console.log(html);

### 注意事项
- 上述代码假设代码块内仅包含两行内容(对应左右两个div),若需处理更多行,可调整内容分割逻辑。
- 若代码块内容包含特殊HTML字符,Showdown会自动转义;如需保留原始字符,可在扩展中添加相应的转义还原处理。

内容的提问来源于stack exchange,提问作者Sergino
相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 04:05:22