Login

Link TemplateTag that checks for permissions and url address

Author:
mlouro
Posted:
May 20, 2009
Language:
Python
Version:
1.0
Tags:
template url permissions address
Score:
0 (after 0 ratings)

This template tag was built to be used in web applications that are permission based. It renders the html for an html link tag if the user has permissions to access the view (if not, returns an empty string). It also checks if the current token is the active url address and, if so, adds class="active" to the html link for presentation purposes.

Example usage:

  1. {% url home as home_url %} {% get_link_if_allowed home_url "Home" %}

  2. {% url project_dashboard project.id as project_dashboard_url %} {% get_link_if_allowed project_dashboard_url "Projects" %}

 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
# -*- coding: utf-8 -*-
from django.template import Node, Library, TemplateSyntaxError, VariableDoesNotExist
from django.core.urlresolvers import reverse, resolve
from django.template.defaulttags import URLNode
from django.contrib.auth.decorators import user_passes_test

register = Library()

class LinkAllowedNode(Node):
    def __init__(self, url, name, permission):
        self.url = url
        self.permission = permission
        self.name = name


    def render(self, context):
        request = context['request']
        url = self.url.resolve(context)

        if self.permission and not request.user.has_perm(self.permission.resolve(context)):
            return ''

        import re
        pattern = "^%s$" % url

        if re.search(pattern, request.path):
            return '<li><a href="%s" title="%s" class="active">%s</a></li>' % (url,self.name.resolve(context),self.name.resolve(context))
        return '<li><a href="%s" title="%s">%s</a></li>' % (url,self.name.resolve(context),self.name.resolve(context))


def get_link_if_allowed(parser, token):

    bits = token.contents.split()
    if len(bits) == 3:
        permission = ''
    elif len(bits) < 3 or len(bits) > 5:
        raise TemplateSyntaxError, "get_link_if_permssions tag takes two or three arguments {% get_link_if_allowed url title permission %}"
    else:
        permission = parser.compile_filter(bits[3])

    return LinkAllowedNode(parser.compile_filter(bits[1]),parser.compile_filter(bits[2]),permission)

get_link_if_allowed = register.tag(get_link_if_allowed)

More like this

  1. Active link by ronnie 3 years, 9 months ago
  2. Ajax form with jQuery by Donn 7 years ago
  3. Showell markup--DRY up your templates by showell 5 years, 9 months ago
  4. Active class for navigation link by cschand 5 years, 11 months ago
  5. Template tag to create mailto links with options by celopes 6 years, 2 months ago

Comments

Please login first before commenting.