extending urlize in django
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"'))
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 :)
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.