Created
October 7, 2011 16:32
-
-
Save danielsokolowski/1270729 to your computer and use it in GitHub Desktop.
Django template tag to hash/map a value to a unique web color --- useful for coloring a list of database entries
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
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 %} | |
<span style='background-color: {% tohexwebcolor client.id %}'>{{client.name}}</span> | |
""" | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment