I'm using Redcarpet's Markdown parser within Rails 4.1 so that staff can write messages to one another with some formatting. I want them to be able to embed youtube videos too. Maybe something like:
Hey, *check out* my video: [VMD-z2Xni8U](youtube)
That would output:
Hey, check out my video: <iframe width="560" height="315" src="//www.youtube.com/embed/VMD-z2Xni8U" frameborder="0" allowfullscreen></iframe>
Is there any way to do this within Redcarpet's Markdown parser? I assume I would have to write a custom parser of some kind? What's the appropriate way to do this, if there is a way? Is there possibly a standard Markdown way of doing this?
The simplest solution seems to be the following. I use http://youtube/VMD-z2Xni8U
in my Markdown to embed a YouTube video. I then allow autolinking in Redcarpet to autolink this.
# /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
I then create a markdown
method to use in any view or controller when displaying markdown content:
# /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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With