我正在使用 Redcarpet's Markdown parser在 Rails 4.1 中,这样员工就可以用某种格式互相写消息。我希望他们也能够嵌入 YouTube 视频。也许是这样的:
Hey, *check out* my video: [VMD-z2Xni8U](youtube)
那将输出:
嘿,结帐 我的视频:
<iframe width="560" height="315" src="//www.youtube.com/embed/VMD-z2Xni8U" frameborder="0" allowfullscreen></iframe>
有没有办法在 Redcarpet 的 Markdown 解析器中做到这一点?我假设我必须编写某种自定义解析器?如果有办法,这样做的合适方法是什么?是否可能有一种标准的 Markdown 方式来做到这一点?
最佳答案
最简单的解决方案似乎如下。我用 http://youtube/VMD-z2Xni8U
在我的 Markdown 中嵌入 YouTube 视频。然后我允许在 Redcarpet 中自动链接以自动链接它。
# /lib/helpers/markdown_renderer_with_special_links.rb
class MarkdownRendererWithSpecialLinks < Redcarpet::Render::HTML
def autolink(link, link_type)
case link_type
when :url then url_link(link)
when :email then email_link(link)
end
end
def url_link(link)
case link
when /^http:\/\/youtube/ then youtube_link(link)
else normal_link(link)
end
end
def youtube_link(link)
parameters_start = link.index('?')
video_id = link[15..(parameters_start ? parameters_start-1 : -1)]
"<iframe width=\"560\" height=\"315\" src=\"//www.youtube.com/embed/#{video_id}?rel=0\" frameborder=\"0\" allowfullscreen></iframe>"
end
def normal_link(link)
"<a href=\"#{link}\">#{link}</a>"
end
def email_link(email)
"<a href=\"mailto:#{email}\">#{email}</a>"
end
end
然后我创建了一个
markdown
显示 Markdown 内容时在任何 View 或 Controller 中使用的方法:# /app/helpers/application_helper.rb
module ApplicationHelper
require './lib/helpers/markdown_renderer_with_special_links'
def markdown(content)
@markdown ||= Redcarpet::Markdown.new(MarkdownRendererWithSpecialLinks, autolink: true, space_after_headers: true, fenced_code_blocks: true)
@markdown.render(content).html_safe
end
end
关于ruby-on-rails - 如何使用 Redcarpet for Rails 在 Markdown 中嵌入 YouTube 视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23051568/