2017-04-19 79 views
0

我正在使用一個靜態網站生成器(Hugo),它將源文件中的所有純文本URL轉換爲超鏈接到相同的URL,例如,如何將嵌入YouTube視頻的超鏈接URL替換爲

<p><a href="https://www.youtube.com/watch?v=xLrLlu6KDss">https://www.youtube.com/watch?v=xLrLlu6KDss</a></p> 

我寧願將它作爲嵌入式視頻。

有足夠的代碼位將明文YouTube網址轉換爲可以工作的嵌入(example),但如何在超鏈接時嵌入它?

或者如果有人可以幫助我將鏈接值與鏈接名稱相同的所有href鏈接轉換爲純粹的URL?例如如何與

https://www.youtube.com/watch?v=xLrLlu6KDss 

回答

0

更換

<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」選擇器僅指向內容區域中的鏈接而不是整個頁面可能是一個好主意。另外,我猜測這對於有很多鏈接的網頁來說可能會很慢;如果是這種情況,您可能需要進行一些性能調整。

+0

是的,如果我提前知道YouTube網址,那可以正常工作。我可能沒有全面解釋 - 我正在研究一個將降價內容放入Hugo站點的系統,所以我希望能夠在運行中自動轉換它們。我可能只是在我將它放入內容之前運行一個正則表達式。 – cogdog

+0

我已經更新了我的答案,以包含類似於您所需的jQuery代碼。以降價做它是最好的方法,但jQuery解決方案也應該起作用。 –

+0

非常感謝!它確實有用,但感覺像是不必要的開銷,而且不得不與未知的視頻維度爭吵。我現在在我的內容目錄上運行兩個正則表達式,用hugo shortcodes替換youtube和vimeo網址,這些網址很好地響應 – cogdog