freshleafmedia / tiptap-parser
dev-master
2024-06-19 15:10 UTC
Requires
This package is auto-updated.
Last update: 2024-09-19 15:39:55 UTC
README
此包简单地将 Tiptap 编辑器 的 JSON 输出转换为 HTML。它与其他包不同,允许您轻松自定义和扩展 HTML 输出。
安装
composer require freshleafmedia/tiptap-parser
基本用法
use FreshleafMedia\TiptapParser\TiptapContent; $tiptapArray = [ 'type' => 'paragraph', 'content' => [ [ 'type' => 'text', 'text' => 'Hello world', ], ], ]; TiptapContent::make($tiptapArray)->toHtml(); // <p>Hello world</p>
自定义节点
use FreshleafMedia\TiptapParser\Nodes\Paragraph; readonly class CustomParagraph extends Paragraph { public function render(): string { return <<<HTML <p class="paragraph"> {$this->renderInnerHtml()} </p> HTML; } } $html = Parser::fromArray($tiptapArray) ->registerNode('paragraph', CustomParagraph::class) ->toHtml(); // <p class="paragraph">Hello world</p>
访问自定义属性
节点通过 fromArray
方法实例化,此方法接收原始数组中的所有数据。
例如给定此数组
[ 'type' => 'paragraph', 'attrs' => [ 'lang' => 'en', ] ]
我们可以轻松地将 lang
属性添加到 p
元素,如下所示
use FreshleafMedia\TiptapParser\Nodes\Paragraph; readonly class LocalisedParagraph extends Paragraph { public function __construct( public string $language, public array $children = [], ) { } public function render(): string { return <<<HTML <p lang="{$this->language}"> {$this->renderInnerHtml()} </p> HTML; } public static function fromArray(array $array): self { return new self( $array['attrs']['lang'] ?? 'en', $array['children'] ?? [], ); } }
纯文本
可以通过 toText
方法提取纯文本。这对于像填充搜索索引这样的任务很有用。
use FreshleafMedia\TiptapParser\TiptapContent; $tiptapArray = [ 'type' => 'paragraph', 'content' => [ [ 'type' => 'text', 'text' => 'Hello world', 'marks' => [ ['type' => 'bold'], ], ], ], ]; TiptapContent::make($tiptapArray)->toHtml(); // <p><strong>Hello world</strong></p> TiptapContent::make($tiptapArray)->toText(); // Hello world