generate nofollow links in RDiscount output

626 Views Asked by At

My rails app is using RDiscount to generate HTML from user-supplied markdown text, and I noticed that the anchor tags don't have rel="nofollow". This is a big issue for me as my app is open to the public. Is there a way to enable nofollow links, or are there better solutions?

Thanks!

4

There are 4 best solutions below

0
On

I needed to do something similar, add target="_new" to all links. Solved it using Kramdown and a custom Kramdown::Converter::Html class.

Define a Kramdown::Converter::Html subclass (kramdown/converter/my_html.rb in some autoload path)

class Kramdown::Converter::MyHtml < Kramdown::Converter::Html
  def convert_a(el, indent)
    el.attr['target'] = '_new'
    super
  end
end

I also have a view helper in app/helpers/application_helper.rb

def markdown(str)
  Kramdown::Converter::MyHtml.convert(Kramdown::Document.new(str).root)[0].html_safe
end

Ideally it should be possible to just use Kramdown::Document.new(str).to_my_html.html_safe but I can't get it to work in rails development mode as Kramdown uses const_defined? to see if a converter is available and that does not trigger the autoloader. Please comment if you know how to fix this.

0
On

There is an open feature request on RDiscount to support modifying links in this fashion.

It is scheduled for one of the upcoming RDiscount 2.1.5.x releases.

0
On

In the mean time, I am using this hack, by re-parsing the RDiscount output and add a rel="nofollow" to each anchor:

def markdown(input)
  html = RDiscount.new(input).to_html
  doc = Nokogiri::HTML::DocumentFragment.parse(html)
  doc.css("a").each do |link|
    link['rel'] = 'nofollow'
  end
  doc.to_html
end

Though I think this should really be handled by the markdown parser.

1
On

I think this is possible only with Kramdown, which is a ruby Markdown parser with extended syntax. You would do that then as shown in the link:

[link](test.html){:rel='nofollow'}