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.
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.
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