Make All hashtags clickable in Template with Templatetags

后端 未结 1 1009
一个人的身影
一个人的身影 2021-01-25 18:15

I want to turn every hashtag in the comment textfield to url so that it will be clickable.

For example, a user submit,

s = \"I can\'t get en         


        
相关标签:
1条回答
  • 2021-01-25 18:51

    You will need to use mark_safe to mark your return value as html. Keep in mind that since you are marking it as safe, you must escape it first. re.sub() is what you were looking for:

    import re
    from django import template
    from django.utils.html import escape
    from django.utils.safestring import mark_safe
    
    register = template.Library()
    
    def create_hashtag_link(tag):
        url = "/tags/{}/".format(tag)
        # or: url = reverse("hashtag", args=(tag,))
        return '<a href="{}">#{}</a>'.format(url, tag)
    
    
    @register.filter()
    def hashtag_links(value):
        return mark_safe(
            re.sub(r"#(\w+)", lambda m: create_hashtag_link(m.group(1)),
                   escape(value)))
    

    Note: We assume that value is text (unescaped), and create_hashtag_link(tag) assumes tag is a word (\w+) and does not need escaping. For creating links to other fragments of text, use format_html() instead of .format()

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