Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extending urlize in django

Tags:

django

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?

like image 266
hymloth Avatar asked Feb 19 '10 10:02

hymloth


3 Answers

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 :)

like image 112
Wojteks Avatar answered Oct 31 '22 20:10

Wojteks


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"'))
like image 16
Simon Steinberger Avatar answered Oct 31 '22 22:10

Simon Steinberger


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.

like image 6
Ignacio Vazquez-Abrams Avatar answered Oct 31 '22 21:10

Ignacio Vazquez-Abrams