Login

middleware: external links open in new window

Author:
christian
Posted:
October 1, 2007
Language:
Python
Version:
.96
Tags:
middleware urls
Score:
3 (after 3 ratings)

Removes all target="..." attributes form hyperlinks, and then adds target="_blank" to all links starting with "http"

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class ExtlinksBlankMiddleware(object):
    '''
    Makes sure all external and only exernal links open in a new window.
    '''
    def __init__(self):
        self.targets = re.compile(r'''target=.\w*.''')
        self.extlinks = re.compile(r'''<a (?P<old>[^>]*http.?://)''')
    def process_response(self, request, response):
        if ("text" in response['Content-Type']):
            response.content = self.targets.sub('', response.content)
            response.content = self.extlinks.sub('<a target="_blank" \g<old>',response.content)
            return response
        else:
            return response

More like this

  1. Add rel=lightbox to all image-links by bartTC 7 years, 5 months ago
  2. Remove self links middleware by svetlyak 7 years, 2 months ago
  3. True links in the admin list by svetlyak 7 years, 10 months ago
  4. CheckedField by oggy 6 years, 9 months ago
  5. Accessing URL variable from within a Form by blacktav 1 year, 10 months ago

Comments

marcob (on February 11, 2010):

Well done!

#

Please login first before commenting.