Created
May 14, 2010 06:55
-
-
Save tkaemming/400888 to your computer and use it in GitHub Desktop.
This file contains 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 copy import copy | |
from hashlib import md5 | |
from urllib import urlencode | |
from django import template | |
from django.conf import settings | |
register = template.Library() | |
class GravatarNode(template.Node): | |
def __init__(self, user, size=None): | |
self.user = template.Variable(user) | |
self.size = size | |
def render(self, context): | |
GRAVATAR_URL = getattr(settings, 'GRAVATAR_URL', | |
'http://www.gravatar.com/avatar/') | |
# For available options, see this URL: http://en.gravatar.com/site/implement/url | |
GRAVATAR_OPTIONS = copy(getattr(settings, 'GRAVATAR_OPTIONS', {})) | |
if self.size is not None: | |
GRAVATAR_OPTIONS['s'] = self.size | |
user = self.user.resolve(context) | |
email = user.email or 'INVALID_EMAIL' | |
return u'%s%s?%s' % ( | |
GRAVATAR_URL, | |
md5(email).hexdigest(), | |
urlencode(GRAVATAR_OPTIONS), | |
) | |
@register.tag | |
def gravatar(parser, token): | |
bits = token.split_contents() | |
if len(bits) == 2: | |
kwargs = { | |
'user': bits[1] | |
} | |
elif len(bits) == 3: | |
kwargs = { | |
'user': bits[1], | |
'size': bits[2] | |
} | |
else: | |
raise template.TemplateSyntaxError, "%r tag requires either one or two argument(s)." % token.contents.split()[0] | |
return GravatarNode(**kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment