开发者

generate nofollow links in RDiscount output

开发者 https://www.devze.com 2023-02-04 06:28 出处:网络
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 p

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 a开发者_如何学Pythonre there better solutions?

Thanks!


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'}


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.


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.


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号