更换
<p><a href="https://www.youtube.com/watch?v=xLrLlu6KDss">https://www.youtube.com/watch?v=xLrLlu6KDss</a></p>
要做到这一点,最好的办法是让雨果使嵌入代码本身。如果您愿意,可以将HTML代码直接放置在降价文档中,或者为了使其更容易,您可以使用shortcode。雨果甚至有一个built-in shortcode for YouTube。
{{< youtube xLrLlu6KDss >}}
如果你把你的降价文件中,雨果将在它生成的页面中嵌入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”选择器仅指向内容区域中的链接而不是整个页面可能是一个好主意。另外,我猜测这对于有很多链接的网页来说可能会很慢;如果是这种情况,您可能需要进行一些性能调整。
是的,如果我提前知道YouTube网址,那可以正常工作。我可能没有全面解释 - 我正在研究一个将降价内容放入Hugo站点的系统,所以我希望能够在运行中自动转换它们。我可能只是在我将它放入内容之前运行一个正则表达式。 – cogdog
我已经更新了我的答案,以包含类似于您所需的jQuery代码。以降价做它是最好的方法,但jQuery解决方案也应该起作用。 –
非常感谢!它确实有用,但感觉像是不必要的开销,而且不得不与未知的视频维度争吵。我现在在我的内容目录上运行两个正则表达式,用hugo shortcodes替换youtube和vimeo网址,这些网址很好地响应 – cogdog