Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails/Redcarpet: Markdown-->HTML with link attributes not working in helper

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.

like image 458
w2bro Avatar asked Nov 26 '25 18:11

w2bro


1 Answers

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.

like image 128
MaximusDominus Avatar answered Nov 28 '25 12:11

MaximusDominus