Login

Current Page Middleware

Author:
brutasse
Posted:
June 23, 2010
Language:
Python
Version:
1.2
Score:
3 (after 3 ratings)

This module provides a middleware that implements a mechanism to highlight a link pointing to the current URL.

Every link on the rendered page matching the current URL will be highlighted with a 'current_page' CSS class.

The name of the CSS class can be changed by setting CURRENT_PAGE_CLASS in the project settings.

Originally done by Martin Pieuchot and Bruno Renié, thanks @davidbgk and @samueladam for improvements & optimizations.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import re

from django.conf import settings
from django.utils.safestring import mark_safe

CLASS = getattr(settings, 'CURRENT_PAGE_CLASS', 'current_page')
CLASS_RE = re.compile(r"""(\bclass\s*=\s*(['"]))""", re.IGNORECASE)
HREF_RE = re.compile(r"""(<a\W[^>]*\bhref\s*=\s*
                         (["'])(.*?)(?<!\\)(["'])[^>]*>)""",
                         re.IGNORECASE + re.VERBOSE)
HTML_TYPES = ('text/html', 'application/xhtml+xml')


class CurrentPageMiddleware(object):
    """
    Middleware that post-processes a response to add a
    class 'current_page' to a link if its href attribute
    matches the current URL.
    """

    def process_response(self, request, response):
        path = request.get_full_path()
        if path.endswith('/'):
            paths = [path, path[:-1]]
        else:
            paths = [path, path + '/']

        if response['Content-Type'].split(';')[0] in HTML_TYPES:

            def add_current_page_class(match):
                """Returns the matched <a href="..."> tag with
                class="current_page """
                tag = match.group()
                if match.group(3) in paths:
                    has_class = CLASS_RE.search(tag)
                    if has_class:
                        tokens = CLASS_RE.split(tag)
                        new_tag = ''.join(tokens[:2]) + '%s ' % CLASS + \
                                ''.join([t for t in tokens[2:] \
                                if t not in ('"', "'")])
                    else:
                        new_tag = tag[:-1] + ' class="%s">' % CLASS
                    return mark_safe(new_tag)
                return tag
            response.content = HREF_RE.sub(add_current_page_class,
                                           response.content)
        return response

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.