6 January 2010

Simple nofollow filter for Markdown (Python)

I just want to share the simple Markdown extension that will add rel=nofollow to all <a> links generated by Markdown. The solution is simplistic, but it is meant to be used in user comments to not drain URL juice out of site or to lower position by bad urls mentioned by users (SEO). The code is based on the idea from Django Snippet 312.


import markdown
import re

R_NOFOLLOW = re.compile('<a (?![^>]*rel=["\']nofollow[\'"])')
S_NOFOLLOW = '<a rel="nofollow" '

class NofollowPostprocessor(markdown.postprocessors.Postprocessor):
def run(self, text):
return R_NOFOLLOW.sub(S_NOFOLLOW, text)

class NofollowExtension(markdown.Extension):
""" Add nofollow for links to Markdown. """

def extendMarkdown(self, md, md_globals):
md.postprocessors.add('nofollow', NofollowPostprocessor(md), '_end')

def makeExtension(configs={}):
return NofollowExtension(configs=configs)

1 komentarze:

  1. Thanks for the script!

    Would you be willing to explain how this would be setup and used? I'm new to Python.

    Thanks,
    Drew
    ReplyDelete