[Answered ]-Make All hashtags clickable in Template with Templatetags

2👍

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

👤Udi

Leave a comment