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

 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. Colorize Filter by empty 6 years, 1 month ago
  2. HTML color code field by b23 5 years, 9 months ago
  3. HTML Hex Color Field by claudelacey 4 years, 10 months ago
  4. A Django form field that accepts an uploaded image and creates a resized image attached with a push-pin by rmisio 2 years, 10 months ago
  5. Pygmentation by alcides 5 years, 9 months ago

Comments

(Forgotten your password?)