Skip to content

Instantly share code, notes, and snippets.

@tkaemming
Created May 14, 2010 06:55
Show Gist options
  • Save tkaemming/400888 to your computer and use it in GitHub Desktop.
Save tkaemming/400888 to your computer and use it in GitHub Desktop.
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