更換
<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