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?
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.
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.
Hi,
You can add a custom filter, as descibed in:
http://docs.djangoproject.com/en/1.1/howto/custom-template-tags/#howto-custom-template-tags
I used this one:
def url_target_blank(text):
return text.replace('<a ', '<a target="_blank" ')
url_target_blank = register.filter(url_target_blank)
Example of usage:
{{ post_body|urlize|url_target_blank }}
Works fine for me :)