Derek Stegelman

Snippet Sunday: Check Group Affiliation in Templates

Sunday snippets are bits of code that I've found useful in past projects. I post them here in hopes that someone else will find them useful. Most of these are Github Gists and you can follow them there too if you want.

I often need to show or hide some piece of functionality for certain groups in web applications. It's hard to check this without some sort of context processor that sends group information to the template on each request. This weeks Sunday Snippet is a template tag you can drop in that will do this for you. As with all Sunday Snippets, check out my Github gist page for this and more. ```python from django import template from django.template import resolve_variable from django.contrib.auth.models import Group

register = template.Library()

@register.tag() def ifusergroup(parser, token): """ Check to see if the currently logged in user belongs to a specific group. Requires the Django authentication contrib app and middleware.

""" try: tag, group = token.splitcontents() except ValueError: raise template.TemplateSyntaxError("Tag 'ifusergroup' requires 1 argument.") nodelist = parser.parse(('endifusergroup',)) parser.deletefirst_token() return GroupCheckNode(group, nodelist)

class GroupCheckNode(template.Node): def init(self, group, nodelist): self.group = group self.nodelist = nodelist def render(self, context): user = resolvevariable('user', context) if not user.isauthenticated: return '' try: group = Group.objects.get(name=self.group) except Group.DoesNotExist: return '' if group in user.groups.all(): return self.nodelist.render(context) return '' ```