the urlize function from django.utils.html converts urls to clickable links. My problem is that I want to append a target="_blank" into the "< href..>", so that I open this link in a new tab. Is there any way that I can extend the urlize function to receive an extra argument? or should I make a custom filter using regexes to do this stuff? Is this efficient?
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 :)
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"'))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With