CKEditor 4 Mentions 插件 `outputTemplate` 深度解析:自定义 @提及插入内容的模板化实现与测试验证

原创2026-10-15 19:03:111,741 阅读
文章标签:前端UI组件

CKEditor 4 Mentions 插件 outputTemplate 深度解析:自定义 @提及插入内容的模板化实现与测试验证

导读

outputTemplate 是 CKEditor 4 Mentions 插件(4.10.0 起引入,对应 issue #1987)中用于自定义选中提及项后插入编辑器内容的 HTML 模板的配置项。本文以仓库中的手动测试用例 tests/plugins/mentions/manual/outputTemplate.md 为起点,完整梳理该功能的配置方法、手动/自动化测试验证路径,并深入 plugins/mentions/plugin.js 与 plugins/autocomplete/plugin.js 源码,剖析 outputTemplate 从配置编译、数据编码到插入编辑器的完整调用链。读完本文,你将能够在自己的编辑器实例中通过几行配置,让提及结果以加粗、链接等任意富文本形式插入正文。

一、功能背景:Mentions 插件与 Autocomplete 的协作关系

Mentions 插件允许用户输入一个标记字符(默认 @)后获得建议项列表,从而不必手动完整输入提及对象。其核心实现位于 plugins/mentions/plugin.js:

CKEDITOR.plugins.add( 'mentions', {
	requires: 'autocomplete,textmatch,ajax',
	instances: [],
	init: function( editor ) {
		var self = this;
		editor.on( 'instanceReady', function() {
			CKEDITOR.tools.array.forEach( editor.config.mentions || [], function( config ) {
				self.instances.push( new Mentions( editor, config ) );
			} );
		} );
	},
	isSupportedEnvironment: function( editor ) {
		return editor.plugins.autocomplete.isSupportedEnvironment( editor );
	}
} );

从源码结构可以看出三个关键事实:

  1. 依赖关系:mentions 插件 requires: 'autocomplete,textmatch,ajax',它本身不实现下拉与插入逻辑,而是为每一条 config.mentions 配置创建 Mentions 实例,每个实例内部再实例化一个 CKEDITOR.plugins.autocomplete 对象;
  2. 配置入口:所有提及规则统一从 editor.config.mentions 数组读取,每项配置对应一个独立实例;
  3. 环境检测:mentions 的 isSupportedEnvironment 直接委托给 autocomplete 插件判断,说明两者运行环境约束完全一致。

outputTemplate 正是由 Mentions 构造函数透传给 autocomplete 的若干配置项之一:

this._autocomplete = new CKEDITOR.plugins.autocomplete( editor, {
	textTestCallback: getTextTestCallback( this.marker, this.minChars, this.pattern ),
	dataCallback: getDataCallback( feed, this ),
	itemTemplate: config.itemTemplate,
	outputTemplate: config.outputTemplate,
	throttle: this.throttle,
	itemsLimit: config.itemsLimit,
	followingSpace: this.followingSpace
} );

二、outputTemplate 是什么:一个配置项、两种表现

outputTemplate 定义的是选中建议项并回车(或按 Tab)提交时,被插入编辑器正文的 HTML 模板。它是 CKEDITOR.template 类型的模板字符串,可以使用 item 对象的任意属性作为占位符。

在 plugins/autocomplete/plugin.js 中,该配置项被编译为模板对象:

/**
 * Template of markup to be inserted as the autocomplete item gets committed.
 *
 * You can use {@link CKEDITOR.plugins.autocomplete.model.item item} properties to customize the template.
 *
 * ```javascript
 * var outputTemplate = `<a href="/tracker/{ticket}">#{ticket} ({name})</a>`;
 * ```
 *
 * @readonly
 * @property {CKEDITOR.template} [outputTemplate=null]
 */
this.outputTemplate = config.outputTemplate !== undefined ? new CKEDITOR.template( config.outputTemplate ) : null;

核心行为差异体现在 getHtmlToInsert 中:

getHtmlToInsert: function( item ) {
	var encodedItem = encodeItem( item );
	return this.outputTemplate ? this.outputTemplate.output( encodedItem ) : encodedItem.name;
}
  • 未配置 outputTemplate(默认值 null):直接插入 encodedItem.name,即纯文本形式的提及名称;
  • 配置了 outputTemplate:以模板渲染 encodedItem 后插入,模板中的 {name}、{id} 等占位符会被替换为 item 对应属性的值。

这里的 encodeItem(plugins/autocomplete/plugin.js#L1531-L1536)会对 item 的所有属性逐一执行 CKEDITOR.tools.htmlEncode,防止用户数据中的 HTML 标签被当作可执行标记注入编辑器,这是模板替换前的重要安全防线。

三、官方手动测试用例:完整步骤与预期结果

仓库中 tests/plugins/mentions/manual/outputTemplate.md 是一份 Bender 框架的手动测试脚本(manual test),用于人工验证 outputTemplate 功能。其头部元数据标注了适用条件:

@bender-tags: mentions, feature, 4.10.0, 1987
@bender-ui: collapsed
@bender-ckeditor-plugins: wysiwygarea, toolbar, basicstyles, mentions
  • 4.10.0:该功能从 CKEditor 4.10.0 开始可用;
  • 1987:关联的 GitHub issue 编号(本功能的来源);
  • wysiwygarea, toolbar, basicstyles, mentions:测试页加载的插件集合,其中 basicstyles 提供 <strong>(加粗)样式支持,是验证加粗插入效果的前提。

2.1 操作步骤

  1. 聚焦编辑器(点击编辑区域);
  2. 输入 @ 触发提及下拉;
  3. 等待下拉列表出现后,按 Enter 键提交选中的建议项。

2.2 期望结果(Expected)

插入的名称是加粗的(Inserted name is bolded)。

2.3 意外结果(Unexpected)

插入的名称是纯文本(Inserted name is a plain text),即 outputTemplate 未生效或配置错误时的表现。

2.4 测试页的实际配置

与测试脚本配套的页面 tests/plugins/mentions/manual/outputTemplate.html 展示了可复制的完整配置:

<div id="editor"></div>

<script>
	var editor = CKEDITOR.replace( 'editor', {
		width: 600,
		mentions: [
			{
				feed: [ 'Anna', 'John', 'Thomas' ],
				outputTemplate: '<strong>{name}</strong>',
				minChars: 0
			}
		]
	} );

	bender.tools.ignoreUnsupportedEnvironment( 'mentions', editor );
</script>

这段配置的要点:

  • feed: <a href="https://link.gitcode.com/i/4a686d97115980de275b2185595cb657" target="_blank"> 'Anna', 'John', 'Thomas' ]:同步数组数据源,mentions 插件会自动为每一项生成 id(从 1 开始递增,见 [getDataCallback 中的 indexArrayFeed);
  • outputTemplate: '<strong>{name}</strong>':提交时将 {name} 替换为实际提及名称,并包裹在 <strong> 标签内,于是正文中出现加粗的 @Anna 等;
  • minChars: 0:输入 @ 后立即触发建议,无需再输入至少 2 个字符(默认值为 2,见下文配置项详解);
  • bender.tools.ignoreUnsupportedEnvironment( 'mentions', editor ):在不支持 autocomplete 的环境中自动跳过该测试。

四、源码级实现原理:从按下 Enter 到 HTML 落地的完整链路

4.1 提交触发与提交键

当提及下拉打开且选中某个建议项后,按下 Enter(键码 13)或 Tab(键码 9)即可提交。默认提交键由 autocomplete_commitKeystrokes 配置定义:

CKEDITOR.config.autocomplete_commitKeystrokes = [ 9, 13 ];

commit 方法(plugins/autocomplete/plugin.js#L419-L451)负责执行插入:

commit: function( itemId ) {
	if ( !this.model.isActive ) {
		return;
	}

	this.close();

	if ( itemId == null ) {
		itemId = this.model.selectedItemId;
		if ( itemId == null ) {
			return;
		}
	}

	var item = this.model.getItemById( itemId ),
		editor = this.editor,
		html = this.getHtmlToInsert( item );

	// Insert space after accepting match (#2008).
	html += this.followingSpace ? '&nbsp;' : '';

	editor.fire( 'saveSnapshot' );
	editor.getSelection().selectRanges( [ this.model.range ] );
	editor.insertHtml( html, 'text' );

	if ( this.followingSpace ) {
		removeLeadingSpace( editor );
	}

	editor.fire( 'saveSnapshot' );
}

关键流程可归纳为四步:

  1. 校验激活状态:模型未激活(下拉未打开)时直接返回,防止误插入;
  2. 生成 HTML:调用上文分析的 getHtmlToInsert(item),依据是否配置 outputTemplate 决定输出模板渲染结果还是纯文本名称;
  3. 选区替换:通过 editor.getSelection().selectRanges( [ this.model.range ] ) 选中当前查询文本(即用户输入的 @An... 区域),再以 editor.insertHtml( html, 'text' ) 整体替换为生成的 HTML。'text' 模式表示插入的是"纯 HTML 文本流";
  4. 快照保护:插入前后分别触发 saveSnapshot,确保该操作可作为一次独立的撤销步骤。

4.2 Mentions 对名称的特殊处理:为什么插入的是 @Anna 而非 Anna

在 getDataCallback 的 resolveCallbackData 中,mentions 插件会为每个 item 的 name 补上标记字符前缀:

function resolveCallbackData( data ) {
	if ( !data ) {
		return;
	}

	// We don't want to change item data, so lets create new one.
	var newData = CKEDITOR.tools.array.map( data, function( item ) {
		var name = mentions.marker + item.name;
		return CKEDITOR.tools.object.merge( item, { name: name } );
	} );

	callback( newData );
}

因此当配置 outputTemplate: '<strong>{name}</strong>' 并选择 Anna 时,模板中的 {name} 实际值为 @Anna,最终插入的是 <strong>@Anna</strong>。这与手动测试"插入的名称是加粗的"的预期完全一致——加粗的是包含 @ 前缀的完整提及文本。

4.3 数据编码顺序:模板替换前的安全处理

getHtmlToInsert 先调用 encodeItem 对 item 全属性做 HTML 转义,再执行 this.outputTemplate.output( encodedItem )。这意味着即使 feed 返回的数据包含 <script> 之类的字符串,最终插入的也是转义后的安全文本。该行为对数组 feed、URL feed 和函数 feed 三种数据源统一生效。

五、outputTemplate 与 itemTemplate:插入内容与下拉展示的分工

outputTemplate 常与 itemTemplate 混淆,两者职责截然不同。仓库中另一份手动测试 tests/plugins/mentions/manual/viewTemplate.md 及其页面 tests/plugins/mentions/manual/viewTemplate.html 专门验证了 itemTemplate 的行为:

mentions: [
	{
		feed: [ 'Anna', 'John', 'Thomas' ],
		itemTemplate: '<li data-id="{id}">item: <strong>{name}</strong></li>',
		minChars: 0
	}
]
配置项 作用对象 生效时机 典型用途
itemTemplate 下拉列表中的展示条目 下拉渲染时 美化建议项外观(如加粗名称、附加图标、自定义布局)
outputTemplate 提交后插入正文的内容 按 Enter/Tab 提交时 让提及文本以链接、加粗、自定义标签等富文本形态进入文档

两份手动测试的预期差异也印证了这一分工:viewTemplate.md 期望"下拉中的名称加粗且带 item: 前缀",而 outputTemplate.md 期望"插入正文的名称加粗"。实践中两者可以组合使用——用 itemTemplate 优化下拉观感,用 outputTemplate 控制最终落地的文档内容。

六、outputTemplate 的进阶用法:自定义 item 与多属性模板

outputTemplate 的占位符并不局限于 {name},只要 item 对象携带的属性都可以被引用。官方自动化测试 tests/plugins/mentions/mentions.js 给出了函数 feed + 自定义属性的组合示例:

// (#1987)
'test custom output template with custom item': function() {
	var editable = this.editor.editable();

	this.editorBot.setHtmlWithSelection( '<p>@An^</p>' );

	this.createMentionsInstance( {
		feed: function( opts, callback ) {
			callback( [ {
				id: 1,
				name: 'Anna',
				surname: 'Doe'
			} ] );
		},
		outputTemplate: '<strong>{name} {surname}</strong>'
	} );

	editable.fire( 'keyup', new CKEDITOR.dom.event( {} ) );
	editable.fire( 'keydown', new CKEDITOR.dom.event( { keyCode: 13 } ) ); // ENTER

	assert.areEqual( '<p><strong>@Anna Doe</strong></p>', editable.getData() );
}

该测试验证了两个要点:

  1. 多属性模板:{name} {surname} 可同时引用 item 的多个字段,渲染结果 @Anna Doe 被加粗包裹;
  2. 提交键:测试通过模拟 keyCode: 13(Enter)的 keydown 事件触发提交,与 autocomplete_commitKeystrokes 默认值 [9, 13] 吻合。

对于 URL 数据源,官方文档示例展示了更贴近真实业务场景的模板——将提及项渲染为链接:

var outputTemplate = `<a href="/tracker/{ticket}">#{ticket} ({name})</a>`;

配合后端返回 { id: 1, name: 'anna87', ticket: 100 } 形式的 JSON 数据(属性结构约定见 plugins/mentions/plugin.js 中 feed 属性说明),即可实现点击可跳转的富文本提及。

七、与 outputTemplate 紧密相关的其他配置项

outputTemplate 只是 mentions 配置定义(CKEDITOR.plugins.mentions.configDefinition)中的一个属性。完整的可配置项在 plugins/mentions/plugin.js 中有系统文档,以下是直接影响模板行为与交互体验的关键项:

配置项 默认值 说明
feed 必填 数据源,三种形式:字符串数组(同步)、URL 字符串(异步 JSON)、回调函数(完全自定义)
marker '@' 触发自动补全的标记字符
minChars 2 标记字符后需再输入的最少字符数;设为 0 则输入标记即触发
pattern 由 marker/minChars 生成 查询匹配正则,默认形如 \@[_a-zA-Z0-9À-ž]{2,}$,支持变音符号字符(见 issue #2491)
outputTemplate null 本文主题:插入内容的 HTML 模板;未配置时插入纯文本名称
itemTemplate 由 view 提供默认 下拉条目的展示模板
throttle 200 输入触发查询的节流毫秒数(异步数据源)
itemsLimit 无限制 下拉显示的最大条目数
caseSensitive false 数组 feed 的查询是否区分大小写
cache true URL feed 响应是否全局缓存(缓存键为编码后的 URL,跨实例共享)
followingSpace 由 autocomplete 决定 4.20.0 起可用,提交后是否自动插入空格

值得注意的默认正则行为(createPattern 实现):

function createPattern( marker, minChars ) {
	// Match also diacritic characters (#2491).
	var pattern = '\\' + marker + '[_a-zA-Z0-9À-ž]';

	if ( minChars ) {
		pattern += '{' + minChars + ',}';
	} else {
		pattern += '*';
	}

	pattern += '$';

	return new RegExp( pattern );
}

当 minChars 为 0 时,正则退化为 \@[_a-zA-Z0-9À-ž]*$,即输入 @ 本身即可匹配——这正是手动测试配置中 minChars: 0 的作用。

八、如何亲手验证:从手动测试到自动化测试

8.1 手动复现路径

  1. 在浏览器中打开 tests/plugins/mentions/manual/outputTemplate.html(该文件可作为独立示例页面运行,或通过 Bender 测试服务器加载);
  2. 聚焦宽度为 600px 的编辑区域,输入 @;
  3. 在下拉出现后按 Enter;
  4. 观察正文:若出现 <strong>@Anna</strong> 样式(视觉上加粗),则功能正常;若为纯文本 @Anna,则说明 outputTemplate 未被正确传递或模板编译失败。

如需对比,可同时运行 viewTemplate.html 观察 itemTemplate 对下拉外观的影响,以及 mentions.html 体验三种 feed(@ 数组、$ URL、# 回调)的完整交互。

8.2 自动化测试佐证

除了手动测试,仓库还提供了覆盖 outputTemplate 行为的自动化单元测试:

自动化测试的存在从侧面印证了 outputTemplate 的三条实现事实:模板按 CKEDITOR.template 编译、item 属性经 HTML 编码后替换、提交时替换查询选区。

九、常见问题与注意事项

  1. 插入的是纯文本而不是富文本:请检查 outputTemplate 是否拼写正确、是否传入正确的配置层级。outputTemplate 位于 config.mentions 数组的每一项内部,而非编辑器顶层配置;
  2. {name} 占位符包含 @ 前缀:mentions 在数据回调阶段就会为 name 拼接 marker,模板中不需要也不应再手动添加 @,否则会出现 @@Anna;
  3. HTML 转义是自动的:item 属性值中的 <、>、& 等字符会被 htmlEncode 转义后再填充进模板,因此模板中不要重复转义,也不要依赖模板注入未转义的原始 HTML;
  4. 未配置模板时的行为是纯文本插入:outputTemplate 默认值为 null,此时 getHtmlToInsert 走 encodedItem.name 分支,插入不带任何标签的纯文本;
  5. 环境兼容性:mentions/autocomplete 对运行环境有要求(isSupportedEnvironment),在不受支持的浏览器中功能不会生效,手动测试页中 ignoreUnsupportedEnvironment 的调用正是为此设计。

十、总结

outputTemplate 是 CKEditor 4 Mentions 插件中连接"选择建议项"与"写入文档内容"的桥梁配置:它通过 CKEDITOR.template 编译、item 属性 HTML 编码、查询选区替换三阶段实现富文本提及插入。本文从官方手动测试用例 outputTemplate.md 出发,先后还原了测试步骤与预期、可复制的页面配置、commit → getHtmlToInsert → insertHtml 的源码链路,并借助 mentions.js 中的自动化测试与 autocomplete 插件 的文档注释,完整呈现了该功能的配置、原理与验证方式。无论你是要在文档中实现加粗提及、跳转链接还是自定义标签格式,outputTemplate 都提供了统一且安全的模板化出口。

登录后查看全文
ckeditor4