内容插件如何在 onContentPrepare 中把文章内的 {youtube id} 标签替换为响应式 iframe?
解读
国内面试官提出此题,核心想验证三点:
- 是否熟悉 Joomla 插件体系,尤其是“内容插件”生命周期;
- 能否在 onContentPrepare 阶段安全、高效地改写文章文本,而不影响后续流程;
- 是否具备“响应式”工程思维——既要兼容 Bootstrap 栅格,又要避免硬编码宽高,同时兼顾国内移动端流量占比高的国情。
题目看似简单,但现场常追问:正则怎么防贪婪?缓存怎么打标签?如果同一篇文章出现 20 个视频,性能如何?因此答案必须给出可落地的类结构、事件优先级、安全校验与性能兜底方案。
知识点
- 内容插件入口:plgContentYoutube 类,触发器 onContentPrepare(context, &article, &page=0)。
- 上下文过滤:只处理 com_content.article 与 com_content.featured,避免后台编辑器预览被污染。
- 正则写法:
\{youtube\s+([a-zA-Z0-9_-]{11})\},i 修饰符,贪婪模式用.*?兜底。 - 响应式模板:采用 16:9 比例容器,外包
<div class="video-responsive">,内嵌 iframe,样式用padding-bottom:56.25%; height:0; overflow:hidden; position:relative;,iframe 绝对定位top:0; left:0; width:100%; height:100%,兼容国内主流 CDN 加速。 - 安全:id 白名单校验
preg_match('/^[a-zA-Z0-9_-]{11}$/', $id),防止注入畸形参数。 - 性能:文章文本超过 10 kB 时先
strpos判断是否存在{youtube,无则提前 return;支持 Joomla 缓存分组com_content.article。 - 多语言:错误提示走
Text::_('PLG_CONTENT_YOUTUBE_NO_ID'),方便后期打包语言文件。 - 事件优先级:默认 0,若与“内容保护”插件冲突,可在 xml 中显式声明
<priority>5</priority>。
答案
<?php
defined('_JEXEC') or die;
use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Language\Text;
class PlgContentYoutube extends CMSPlugin
{
protected $autoloadLanguage = true;
public function onContentPrepare($context, &$article, &$params, $page = 0)
{
// 1. 上下文过滤
if (!in_array($context, ['com_content.article', 'com_content.featured'])) {
return;
}
// 2. 快速短路
if (strpos($article->text, '{youtube') === false) {
return;
}
// 3. 正则替换
$article->text = preg_replace_callback(
'/\{youtube\s+([a-zA-Z0-9_-]{11})\}/i',
function ($match) {
$id = $match[1];
if (!preg_match('/^[a-zA-Z0-9_-]{11}$/', $id)) {
return '<!-- Invalid YouTube ID -->';
}
$iframe = '<div class="video-responsive">'
. '<iframe src="https://www.youtube.com/embed/' . $id . '" '
. 'frameborder="0" allowfullscreen></iframe></div>';
// 4. 插入响应式样式(首次加载时)
static $cssInjected = false;
if (!$cssInjected) {
$style = '<style>.video-responsive{position:relative;padding-bottom:56.25%;height:0;overflow:hidden}'
. '.video-responsive iframe{position:absolute;top:0;left:0;width:100%;height:100%}</style>';
$iframe = $style . $iframe;
$cssInjected = true;
}
return $iframe;
},
$article->text
);
}
}
安装包必备文件:
youtube.xml声明<files>、<languages>、<media folder="media/plg_content_youtube">把 css 拆出可缓存。- 语言文件
plg_content_youtube.ini写PLG_CONTENT_YOUTUBE_NO_ID="视频ID非法"。
拓展思考
- 如果客户要求“懒加载 + 封面图”,可先在 onContentPrepare 阶段替换为占位图与 data-id,再借助
onAfterRender把 JS 注入页面底部,IntersectionObserver 触发真实 iframe 加载,减少首屏请求 300 KB。 - 国内网络偶发 YouTube 无法访问,可在插件参数里增加“国内镜像开关”,自动替换为
https://www.youtube.com/embed/{id}?rel=0&showinfo=0,并提示编辑者“如需合规请转存国内视频平台”。 - 当文章被 Joomla 缓存时,记得在替换逻辑里加
JFactory::getApplication()->setHeader('X-Video-Processed', '1'),方便调试;同时把{youtube}标签留在缓存文件里,避免缓存碎片过多。 - 若网站启用 CDN(如阿里云全站加速),样式文件应放入
media/plg_content_youtube/css/responsive.css,并在插件onContentBeforeSave事件里把版本号写入文件名,防止样式更新延迟。