Login

middleware: external links open in new window

Author:
christian
Posted:
October 1, 2007
Language:
Python
Version:
.96
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. Template tag - list punctuation for a list of items by shapiromatron 9 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

marcob (on February 11, 2010):

Well done!

#

Please login first before commenting.