【问题标题】:How to embed a YouTube video in Markdown with Redcarpet for Rails?如何使用 Redcarpet for Rails 在 Markdown 中嵌入 YouTube 视频?
【发布时间】:2014-04-14 03:40:00
【问题描述】:

我在 Rails 4.1 中使用Redcarpet's Markdown parser,以便员工可以通过某种格式将消息相互写入。我希望他们也能够嵌入 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 方式来执行此操作?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 markdown redcarpet ruby-on-rails-4.1


    【解决方案1】:

    最简单的解决方案似乎如下。我在 Markdown 中使用 http://youtube/VMD-z2Xni8U 来嵌入 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 方法,以便在显示降价内容时在任何视图或控制器中使用:

    # /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
    

    【讨论】:

    猜你喜欢
    • 2012-02-18
    • 2011-08-10
    • 2015-02-27
    • 2012-01-06
    • 2012-12-20
    • 2021-11-18
    • 2017-09-01
    • 2011-03-16
    • 2021-02-02
    相关资源
    最近更新 更多