extending urlize in django

后端 未结 4 1178
生来不讨喜
生来不讨喜 2020-12-25 12:29

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 ope

相关标签:
4条回答
  • 2020-12-25 12:47

    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.

    0 讨论(0)
  • 2020-12-25 12:57

    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"'))
    
    0 讨论(0)
  • 2020-12-25 13:02

    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.

    0 讨论(0)
  • 2020-12-25 13:04

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

    0 讨论(0)
提交回复
热议问题