[Django]-Extending urlize in django

6👍

There is no capability in the built-in urlize() to do this. Due to Django’s license you can copy the code of django.utils.html.urlize and django.template.defaultfilters.urlize into your project or into a separate app and use the new definitions instead.

68👍

You can add a custom filter, as described here:

I used this one:

# <app name>/templatetags/url_target_blank.py

from django import template
register = template.Library()

def url_target_blank(text):
    return text.replace('<a ', '<a target="_blank" ')

url_target_blank = register.filter(url_target_blank, is_safe = True)

Example of usage:

{% load url_target_blank %}
...
{{ post_body|urlize|url_target_blank }}

Works fine for me 🙂

16👍

Shortest version, that I use in my projects. Create a new filter, that extends the default filter of Django:

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
from django.utils.html import urlize as urlize_impl

register = template.Library()

@register.filter(is_safe=True, needs_autoescape=True)
@stringfilter
def urlize_target_blank(value, limit, autoescape=None):
    return mark_safe(urlize_impl(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape).replace('<a', '<a target="_blank"'))

-4👍

You shouldn’t add target="_blank" to your links, it’s deprecated. Users should decide themselves if where they want to open a link.

You can still open the link with unobtrusive JavaScript like so (using jQuery):

$('.container a').click(function(e){e.preventDefault();window.open(this.href);});

That said, you could write your own filter, but you’d have to copy a lot of code from django.utils.html.urlize, not really DRY.

Leave a comment