Creating a template filter to humanize URLs

Usually, common web users enter URLs in address fields without protocol and trailing slashes. In this recipe, we will create a humanize_url filter that is used to present URLs to the user in a shorter format, truncating very long addresses, similar to what Twitter does with the links in the tweets.

Getting ready

Similar to the previous recipes, we will start with the utils app that should be set in INSTALLED_APPS in the settings and contain the templatetags package.

How to do it...

In the FILTERS section of the utility_tags.py template library in the utils app, let's add a humanize_url filter and register it, as shown in the following code:

# utils/templatetags/utility_tags.py # -*- coding: UTF-8 -*- from ...

Get Web Development with Django Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.