如何将带有标题的图像插入CKEditor 5中的自定义元素?

时间:2018-11-08 13:08:34

标签: javascript ckeditor ckeditor5

我正在尝试在自定义标签内插入图片元素。但是图像设置不正确。我定制了ckeditor的图片上传插件。

原始上传插件有以下几行:

const imageElement = writer.createElement('image', { uploadId: loader.id });
const insertAtSelection = findOptimalInsertionPosition(doc.selection);
editor.model.insertContent(imageElement, insertAtSelection);

像这样在dom树中添加图像:

<h2>TITLE</h2>
<figure class="image ck-widget ck-widget_selected" contenteditable="false">
    <img src="EXAMPLE/URL" title="" style="">
    <figcaption class="ck-editor__editable ck-editor__nested-editable ck-placeholder" contenteditable="true" data-placeholder=""><br data-cke-filler="true"></figcaption>
</figure>

我更换了插件。当我上传图片时,以下代码行正在运行:

const imageElement = writer.createElement('image', { uploadId: loader.id });
writer.appendElement('content', { 'guid': guid }, parent);
content = parent.getChild(parent.childCount - 1);
writer.append(imageElement, content);
writer.setSelection(content.getChild(content.childCount - 1), 0);

我的代码像这样将图像插入dom树:

<h2>TITLE</h2>
<content>
    <figure class="image ck-widget" contenteditable="false">
        <img>
    </figure>
</content>

如何设置图像属性和标题?我怀疑insertContent。我尝试运行insertContent,但不知道应该将什么作为位置参数发送到insertContent。如果我使用findOptimalInsertionPosition(doc.selection),则图像会添加到<content>之外。

1 个答案:

答案 0 :(得分:1)

定义架构

首先,您需要确保自定义模型元素中允许使用<image>。如果您是这样注册的:

editor.model.schema.register( 'custom', {
    allowContentOf: '$root',
    allowWhere: '$block'
} );

那你就好了。由于<$root>允许包含<image>,因此您的<custom>将允许<image>

您可以在Schema deep dive指南中阅读有关编写模式规则的更多信息。

模型结构

现在,您询问如何设置图像的标题。要了解这一点,您需要询问模型中图像的结构是什么。答案将是–与视图中的视图有很大不同:

<image src="...">
    <caption>Caption text</caption>
</image>

这就是您要创建的结构,以便插入带有标题的图像。

在给定位置插入图像

插入任意内容的最佳方法是editor.model.insertContent(),因为它可以处理两件事:

  • 在插入后将文档选择设置到所需的位置(至少从粘贴状的情况开始)
  • 确保将要插入的内容插入到架构允许的位置(这就是为什么我们需要首先配置架构)的原因。

model writer methods都不做这两个事情,因此除非您确切知道应该在哪里插入图像以及如何设置选择,否则不要使用它们。

那么,如何使用insertContent()

editor.model.change( writer => {
    const image = writer.createElement( 'image', { src: '...' } );
    const caption = writer.createElement( 'caption' );

    writer.appendText( 'Caption text', caption );
    writer.append( caption, image );


    // Option 1: If you have the <custom> element by reference:
    const positionInCustom = Position.createAt( customElement, 0 );

    editor.model.insertContent( image, positionInCustom );

    // In this case, we still have to set the selection because we haven't
    // passed document selection to `insertContent()` but a specific position.
    writer.setSelection( image, 'on' );


    // Option 2: Assuming that the document selection is somewhere
    // in your <custom> element you might do this (image will be inserted
    // at the document selection position):

    editor.model.insertContent( image );
} );

有关各种使用方法,请参见editor.model.insertContent()文档。

相关问题