如何使用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}
注册并使用扩展
初始化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
相关产品推荐
相关产品推荐

