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.
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.
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 __future__ import unicode_literals
import re
from django import template
register = template.Library()
### FILTERS ###
@register.filter
def humanize_url(url, letter_count):
""" Returns a shortened human-readable URL """
letter_count = int...