3

I've got a function in my ApplicationHelper, as well as an exact duplicate in a controller for prerendering. Prerendering creates the links the way I want, with target="_blank", but rendering on the spot does not. My code is as follows:

require 'redcarpet'

module ApplicationHelper
  def markdown(text)
    rndr = Redcarpet::Render::HTML.new(:link_attributes => Hash["target" => "_blank"])
    markdown = Redcarpet::Markdown.new(
                rndr,
                :autolink => true,
                :space_after_headers => true
              )
    return markdown.render(text).html_safe
  end
end

Running this in the rails console also renders links as normal, without the link attributes. Identical code in my controller works as expected.

w2bro
  • 1,016
  • 1
  • 11
  • 36
  • 1
    I can't help with the problem, but thank you for the strategy on adding the `target` attribute via the renderer options. Since I pre-render everything that worked great for me. – Charles Worthington Mar 20 '13 at 17:13

1 Answers1

1

I got this to work using a custom markdown generator (redcarpet v 3.1.2)

lib/my_custom_markdown_class.rb
class MyCustomMarkdownClass < Redcarpet::Render::HTML
  def initialize(extensions = {})
    super extensions.merge(link_attributes: { target: "_blank" })
  end
end

then use it like this

app/helpers/application_helper.rb
def helper_method(text)
  filter_attributes = {
      no_links:    true,
      no_styles:   true,
      no_images:   true,
      filter_html: true
    }

  markdown = Redcarpet::Markdown.new(MyCustomMarkdownClass, filter_attributes)
  markdown.render(text).html_safe
end

Alternately, you can put this helper_method in your model, and set the filter_attributes as a class variable.

MaximusDominus
  • 2,017
  • 18
  • 11