2017-04-19 109 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