This would probably be best served by a custom template filter:

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters