Created
July 30, 2012 17:34
-
-
Save danielsokolowski/3208570 to your computer and use it in GitHub Desktop.
Returns an html string node useful for providing a visual cue to the permission group required; django-guradian required.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template, template | |
from django.contrib.auth.models import Group | |
from guardian.shortcuts import get_groups_with_perms | |
register = template.Library() | |
class ObjectGroups(template.Node): | |
""" | |
Returns an html string node useful for providing a visual cue to the | |
permission group required. | |
Example of usage (assuming ``flatpage`` is available from *context*):: | |
<h1>{% obj_groups flatpage %}{{flatpage.title}}</h1> | |
would result in: | |
<h1><span class='clsPaid clsRegister [cls...]'> </span>{{flatpage.title}}</h1> | |
""" | |
def __init__(self, obj): | |
self.obj = obj # resolved in render method as needed | |
def render(self, context): | |
### check against an instance or a model class | |
instance = template.Variable(self.obj).resolve(context) | |
instance_groups = get_groups_with_perms(instance) | |
html = '<span title="Access Level: %s" class="%s"> </span>' | |
titles = '' | |
classes = '' | |
for group in instance_groups: | |
titles = titles + '%s ' % group.name | |
classes = classes + 'cls%s ' % group.name | |
html = html % (titles, classes) | |
return html | |
@register.tag # this is just synonym with register.tag('get_obj_groups', get_obj_groups) | |
def obj_groups(parser, args): | |
tag_template_syntax = "Tag's syntax is {%% %s <obj_instance> %%}" | |
try: | |
# split_contents() knows not to split quoted strings. | |
tag_name, obj = args.split_contents() | |
except ValueError: | |
raise template.TemplateSyntaxError(tag_template_syntax % args.contents.split()[0]) | |
return ObjectGroups(obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment