oberon/quill-rendering

渲染 Quill 编辑器的 'insert' Delta。受 D. Blackborough 的 Quill Renderer 包启发

v1.0.0 2018-09-12 15:49 UTC

This package is auto-updated.

Last update: 2024-09-13 22:44:50 UTC


README

安装

使用 composer

composer require oberon/quill-rendering

使用方法

$quillOps = "{\"ops\":[
    {\"insert\":\"Lorem ipsum dolor sit amet, \"},
    {\"insert\":\" consectetur\",\"attributes\":{\"bold\":true}},
    {\"insert\":\" adipiscing elit. Sed volutpat lectus non \"},
    {\"insert\":\"pellentesque volutpat\",\"attributes\":{\"italic\":true}},
    {\"insert\":\". Phasellus in lectus pulvinar lorem vestibulum pellentesque.\"}
]}";

try {
    $quill = new RenderQuill();
    $quill->setParsers(\Oberon\Quill\Render\Html\DefaultHtmlParsers::get());
    $quill->load($quillOps);
    echo $quill->render(true);
} catch (Exception $e) {
    echo $e->getMessage();
}

输出应为

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed volutpat lectus non pellentesque volutpat. Phasellus in lectus pulvinar lorem vestibulum pellentesque.

最重要的组件

  • 渲染器

    具有 render 函数,该函数返回一个包含格式化内容的字符串

  • 解析器

    当给定 Quill oprenderers[] 时,如果 op 被处理并且已将适当的 Renderer 添加到提供的 renderers[],则返回 true,否则返回 false

方便的类/方法

DefaultHtmlParsers::get() 返回一个用于大多数基本 HTML 功能的 Parser[],包括

  • 粗体
  • 下划线
  • 删除线
  • 斜体
  • 有序/无序列表
  • 链接
  • 图片
  • 标题
  • 下标/上标

HtmlParser::withQuill($quillOps) 将使用 DefaultHtmlParsers 渲染提供的 Quill 文本。

添加自定义解析器和渲染器

示例:您想用 <b> 代替 <strong> 来表示粗体。

  1. 创建一个渲染器
class Bold implements Renderer {
	
	private $text;
	
	public function __construct($insert) {
		$this->text = $insert;
	}
	
	public function render() {
		return '<b>'.$this->text.'</b>';
	}
}
  1. 创建一个解析器
class BoldParser implements Parser {
	
	public function handleOp(array $op, array & $renderers) {
		
		//Check if your parser is going to handle the op
		if (array_key_exists('attributes', $op)
			&& is_array($op['attributes'])
			&& is_string($op['insert'])
			&& array_key_exists(Attribute::BOLD, $op['attributes'])) {
			
			//Instantiate your Bold Renderer
			$boldRenderer = new Bold($op['insert']);
			
			//It is inline, so add it to a Paragraph-block. The InlineUtil can do that
			InlineUtil::addToParagraph($boldRenderer, $renderers);
			
			return true;
		} else {
			// If your parser does not handle the op return false;
			return false;
		}
	}
}
  1. 将解析器注册到 RenderQuill 中
//Start with the other HTML parsers
$parsers = DefaultHtmlParsers::get();

//Add to the beginning of the array,
//so it is checked before BasicHtmlParser which would also handle the bold attribute
$parsers = array_unshift($parsers, new BoldParser());

$quill = new RenderQuill();
//register
$quill->setParsers($parsers);

注意:此代码仅为示例,使用时需要修改。例如:此代码不处理当 attributes 包含 bold 和其他属性的情况。

备注

load 方法立即使用提供的 Parsers,因此应首先设置解析器。

除了插入之外还存在其他 Ops:这些将不会被渲染。请使用 https://packagist.org.cn/packages/oberon/quill-delta 上的 Quill-Delta 库