Source

dotim / dotim / blog / templatetags / colorful.py

Full commit
from django import template
from django.conf import settings

register = template.Library()

COLORS = (
    '88f',
    '8bbbdd',
    '76cdab',
    '6d6',
    '98c888',
    'b48',
    'c89888',
    'f88',
)


def bitify(text, length=8):
    """Returns a list of ``length`` elements, which length depends on the
    length of ``text``."""
    bits_length = len(text) / length
    extra_bits = len(text) - bits_length * length

    bitified = []
    index = 0
    for element in range(length):
        if element < extra_bits:
            add = 1
        else:
            add = 0

        new_index = index + bits_length + add
        bitified.append((text[index:new_index], COLORS[element]))
        index = new_index
    return bitified


class ColorfulNode(template.Node):

    def __init__(self):
        pass

    def render(self, context):
        chunks = bitify(settings.DOTIM_TITLE)
        rendered = ''
        for (text, color) in chunks:
            rendered += '<span style="color: #%s;">%s</span>' % (color, text)
        return rendered


@register.tag
def colored_title(parser, token):
    return ColorfulNode()