Login

Current Page Middleware

Author:
brutasse
Posted:
June 23, 2010
Language:
Python
Version:
1.2
Tags:
middleware current-page
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. Active class for navigation link by cschand 5 years, 5 months ago
  2. Using URLs for highlighting sections in menu by diverman 4 years, 6 months ago
  3. template tag for highlighting currently active page by adunar 6 years, 4 months ago
  4. YUI Loader as Django middleware by akaihola 6 years, 10 months ago
  5. Remove self links middleware by svetlyak 6 years, 10 months ago

Comments

Please login first before commenting.