hbryan / quill-delta-parser
一个PHP库,用于将Quill Deltas解析为HTML
Requires (Dev)
- phpunit/phpunit: ^7.3
This package is not auto-updated.
Last update: 2024-09-27 06:55:55 UTC
README
一个PHP库,用于将Quill WYSIWYG编辑器的deltas解析为HTML - 具有灵活性和可扩展性,适用于自定义元素。每个元素都通过相同的机制解析,这使得扩展和理解变得容易。
什么是Quill?Quill是一个免费的开源WYSIWYG编辑器,专为现代网络构建。凭借其模块化架构和表达式的API,它可以完全自定义以满足任何需求。
安装
该包仅通过composer提供
composer require nadar/quill-delta-parser
使用方法
use nadar\quill\Lexer; $lexer = new Lexer($json); // echoing the html for the given json ops. echo $lexer->render();
其中$json
是Quill的ops json数组,例如
{ "ops": [ { "insert": "Hello" }, { "attributes": { "header": 1 }, "insert": "\n" }, { "insert": "\nThis is the php quill " }, { "attributes": { "bold": true }, "insert": "parser" }, { "insert": "!\n" } ] }
这将渲染以下HTML
<h1>Hello</h1> <p><br></p> <p>This is the php quill <strong>parser</strong>!</p>
扩展解析器
为了通过添加您自己的监听器来扩展解析器(如果您使用的是生成自定义delta代码的Quill插件,这种情况可能发生),您必须决定它是
- 内联元素:用新解析的内容替换内容,这在处理Quill扩展时通常是这种情况。
- 块元素:使用标签包围整个输入的块元素,例如标题。
一个提及插件的示例,它生成以下delta {"insert":{"mention":{"id":"1","value":"Basil","denotationChar":"@"}}}
一个内联插件可能如下所示
class Mention extends InlineListener { /** * {@inheritDoc} */ public function process(Line $line) { // check if input is json, decodes to an array and checks if the key "mention" // exsts, if yes return the value for this key. $mention = $line->insertJsonKey('mention'); if ($mention) { // use default inline behavior, updates the content and append to next "block" element. // the value in this example would be "<mention>Basil</mention>". $this->updateInput($line, '<mention>'.$mention['value'].'</mention>'); } }
现在注册监听器
$lexer = new Lexer($json); $lexer->registerListener(new Mention); echo $lexer->render();
覆盖内置监听器
某些监听器(图片、视频、颜色)产生的HTML输出可能不适合您的用例,因此您可以选择覆盖这些插件的属性,例如使用图片标签的示例
$image = new Image(); $image->wrapper = '<img src="{src}" class="my-image" />'; // override the default plugin from the lexer: $lexer = new Lexer($json); $lexer->registerListener($image); echo $lexer->render();
调试
有时处理delta以及数据是如何解析的是非常难以调试和理解的。因此,您可以使用调试器类,该类将打印一个表格,显示有关数据如何解析的信息。
$lexer = new Lexer($json); $lexer->render(); // make sure to run the render before call debugPrint(); $debug = new Debug($lexer); echo $debug->debugPrint();
还有一个内置的docker compose文件,它提供了对output.php文件的访问。output.php有助于在显示渲染内容的同时直接使用quill编辑器写入内容,包括所有调试信息。要运行此docker webserver,请在您的克隆的根目录中执行以下命令
docker-compose up
并在浏览器中访问https://:5555/
。