import re import hashlib from django import template register = template.Library() class ToHexWebColorNode(template.Node): def __init__(self, vartoconvert, varnametostoreas=False): self.vartoconvert = template.Variable(vartoconvert) self.varnametostoreas = varnametostoreas def render(self, context): try: actual_vartoconvert = self.vartoconvert.resolve(context) except template.VariableDoesNotExist: raise Exception(self.vartoconvert) return '' hexcolor = '#' + hashlib.md5(str(actual_vartoconvert)).hexdigest()[-6:] if self.varnametostoreas: context[self.varnametostoreas] = hexcolor return '' else: return hexcolor def tohexwebcolor(parser, token): """ This tag will take a value (castable to string) and map it to a unique hex web color. Usage:: {% load tohexwebcolor %} {% tohexwebcolor context-variable %} --- outputs a webhex color with the hash (#) prefix {% load tohexwebcolor %} {% tohexwebcolor context-variable as "variable-name" %} --- puts the variable into template context Example:: Template context contains {{client}} model instance. {% load tohexwebcolor %} {{client.name}} """ try: # split_contents() knows not to split quoted strings. tag_name, bits = token.split_contents() except ValueError: raise template.TemplateSyntaxError("Incorrect tag arguments. " "Usage: {%% %r context-variable as \"varname\" %%} OR {%% %r context-variable %%}" % token.contents.split()[0] ) if (isinstance(bits, list) and (len(bits) > 3 or (len(bits)== 3 and bits[1] != 'as'))): raise template.TemplateSyntaxError("Incorrect tag arguments. " "Usage: {%% %s context-variable as \"varname\" %%} OR {%% %s context-variable %%} %s " % (tag_name,tag_name, bits) ) if len(bits)== 3: # tag called in 'as' mode we know bits[1] is as var_name = bits(1) return ToHexWebColorNode(bits[0], bits[2]) return ToHexWebColorNode(bits) # only one variable passed register.tag('tohexwebcolor', tohexwebcolor)