# christian kaula

about me

Picture of Christian Kaula

Hi there, my name is Chris and I'm a student of Media Informatics. I am a lazy coder which makes me always search for tools that save time. Besides that I do all kinds of things web for money and/or fun.

contact

You can contact me via contact form if you want to get in touch with me. Further I can be found on Xing, Twitter, djangopeople.net and djangogigs.net.

Django Template Tag to Shorten URLs Like Google

Friday 12. March 2010

Need to shorten your URLs like Google does? Something like http://example.com/some/really/long/path/ to http://example.com/.../path/? Here's my simplistic approach:

# -*- encoding: utf-8 -*-

from django import template
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
import re

register = template.Library()

@register.filter
def fancyurlize(value, arg):
    length = int(arg)

    text = value
    for char in (u'%', u'?'):
        arr = value.split(char)
        if len(arr) > 1:
            text = arr[0]

    if len(text) > length:
        arr = re.split(r'(?<!/)/(?!/)', text)
        if len(arr) > 2:
            text = u'/'.join((arr[0], u'...', arr[-1]))

    if len(text) > 0 and text[-1] != u'/':
        text = u''.join((text, u'/'))

    return_value = u'<a href="%s" target="_blank">%s</a>' % (
        conditional_escape(value),
        conditional_escape(text),
    )
    return mark_safe(return_value)

fancyurlize.is_safe = True