Login

Django template tag to hash/map a value to a unique web color.

Author:
danielsokolowski
Posted:
November 9, 2011
Language:
Python
Version:
1.3
Score:
0 (after 0 ratings)

Just a quick and dirty solution I needed to uniquely color code entries in a selection form list.

It uses the hashlib to generate it's coloring.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.