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:
-
{% url home as home_url %} {% get_link_if_allowed home_url "Home" %}
-
{% 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
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.