D. v. Baboon
D. v. Baboon

Reputation: 53

Markdown external image links with Redcarpet

I am using the redcarpet gem to markdown user generated text and would like to show images of external links/image hosts. So far, I have tried something like this:

def markdown(text)
   options = { ... }
   extension = { ... }
   text.gsub!(/(https?:\/\/[\S]*.jpg)/, '<img src="\1" width="100%">')
   renderer = Redcarpet::Render::HTML.new(options)
   markdown = Redcarpet::Markdown.new(renderer, extensions)
   markdown.render(text).html_safe
end

However, I would like to escape_html or filter_html, because injecting </div>, ids, and classes can really mess up the site. This would remove the image tag.

Is there any better way to go about rendering external images while keeping the HTML safe?

Upvotes: 2

Views: 1411

Answers (1)

Michael Gaskill
Michael Gaskill

Reputation: 8042

Something like this:

require "redcarpet"
require "action_view"

class HTMLBlockCode < Redcarpet::Render::HTML
  include ActionView::Helpers::AssetTagHelper

  def image(link, title, alt_text)
    image_tag(link, title: title, alt: alt_text, width: "100%")
  end
end

def markdown(text)
   renderer = HTMLBlockCode.new
   text.gsub!(/(https?:\/\/[\S]*.jpg)/, '![](\1)')
   markdown = Redcarpet::Markdown.new(renderer)
   markdown.render(text)
end

text = File.read("rc_test.md")

puts markdown(text)

This installs a custom image renderer on RedCarpet, which adds a width="100%" attribute to your image elements. It also converts bare image links to markdown-recognized image links in the gsub call. This results in an embedded image url being rendered like this:

<img width="100%" src="http://www.gettyimages.pt/gi-resources/images/Homepage/Hero/PT/PT_hero_42_153645159.jpg" />

And you don't have to change your markdown document in any way; it's automagically delicious.

Upvotes: 1

Related Questions