首页 > 解决方案 > 如何将代码标签放在 quill pre 标签内

问题描述

我正在尝试格式化pre带有块的羽毛笔标签以code进行格式化。

所以,例如,我想要这个:

<pre>
  <code>
    ...my code
  </code>
</pre>

默认情况下,Quill 会删除您直接添加到 DOM 的任何内容,因此您必须在 Quill 中执行此操作。

我用这个潜在的代码找到了这个,但它没有添加代码块。它并没有真正做任何事情。

var BlockEmbed = Quill.import('blots/block/embed');

class CustomCode extends BlockEmbed {
    static create(value) {
        let { lang, content } = value;
        let node = super.create(value);
        const code = document.createElement('code');
        code.setAttribute('class', lang);
        code.textContent = content;
        node.appendChild(code);
        return node;
    }

    static value(node) {
        return {
            lang: node.firstChild.getAttribute('class'),
            content: node.firstChild.innerText
        };
    }
}
CustomCode.blotName = 'code-custom';
CustomCode.tagName = 'pre';

Quill.register('modules/CustomCode', CustomCode);

var editor = new Quill("#editor", {
    modules: {
        syntax: true
    },
    theme: "bubble"
});

有什么想法,还是我错过了什么?

标签: codeblocksquill

解决方案


你几乎做对了。

为了让它工作,只需要:

  • 注册它有点不同Quill.register(CustomCode);
  • 调整CustomCode类以反映该create方法将字符串作为输入并且该方法应返回标签value内的文本内容这一事实code
  • 调整新创建的编辑器的工具栏,以确保我们有一个按钮为我们提供新功能
  • 稍微设计一下那个按钮

我在 StackBlitz 上准备了一个演示来说明这些要点。

为了尝试“自定义代码”功能,请单击编辑器工具栏中的“代码”按钮并粘贴/键入您的代码段,然后点击确定。

这是一个示例片段:function something() {console.log('It works');}

如果我们检查 DOM 树,我们可以看到您最初的设想: 在此处输入图像描述


推荐阅读