最好的方法是让 Hugo 自己制作嵌入代码。如果您愿意,您可以将 HTML 代码直接放在 markdown 文档中,或者为了更容易,您可以使用shortcode。Hugo 甚至有一个内置的 YouTube 短代码。
{{< youtube xLrLlu6KDss >}}
如果你把它放在你的 Markdown 文档中,Hugo 会在生成页面时嵌入 YouTube 视频,它不需要任何自定义 jQuery 代码。
编辑:
如果你绝对必须用 JavaScript 来做这件事,你可以做这样的事情。(注意:这个例子需要 jQuery。)
$("a").each(function () {
// Exit quickly if this is the wrong type of URL
if (this.protocol !== 'http:' && this.protocol !== 'https:') {
return;
}
// Find the ID of the YouTube video
var id, matches;
if (this.hostname === 'youtube.com' || this.hostname === 'www.youtube.com') {
// For URLs like https://www.youtube.com/watch?v=xLrLlu6KDss
matches = this.search.match(/[?&]v=([^&]*)/);
id = matches && matches[1];
} else if (this.hostname === 'youtu.be') {
// For URLs like https://youtu.be/xLrLlu6KDss
id = this.pathname.substr(1);
}
// Check that the ID only has alphanumeric characters, to make sure that
// we don't introduce any XSS vulnerabilities.
var validatedID;
if (id && id.match(/^[a-zA-Z0-9]*$/)) {
validatedID = id;
}
// Add the embedded YouTube video, and remove the link.
if (validatedID) {
$(this)
.before('<iframe width="200" height="100" src="https://www.youtube.com/embed/' + validatedID + '" frameborder="0" allowfullscreen></iframe>')
.remove();
}
});
这会遍历页面中的所有链接,检查它们是否来自 YouTube,找到视频 ID,验证 ID,然后将链接转换为嵌入视频。将“a”选择器调整为仅指向内容区域中的链接而不是整个页面可能是一个好主意。另外,我猜这对于有很多链接的页面可能会很慢;如果是这种情况,您可能需要进行一些性能调整。