使用模板标签使模板中的所有主题标签均可点击 [英] Make All hashtags clickable in Template with Templatetags
问题描述
我想将 comment
文本字段中的每个主题标签都转换为 url,以便它可以被点击.
I want to turn every hashtag in the comment
textfield to url so that it will be clickable.
例如,用户提交,
s = "I can't get enough of #SO because #developers are very #supportive"
我希望它在模板中像这样返回,
I want it to return like this in template,
I can't get enough of #SO because #developers are very #supportive
通过嵌入 {hashtag} 可以显示整个文本和所有主题标签的位置.
Where whole text will display and all hashtag will be clickable by embedding {hashtag}.
我尝试了下面的模板标签代码,但它不会返回带有文本的主题标签.它只会返回这个,
I tried the below templatetags code but it won't return the hashtags with the text. It will only return this,
<a href='http://example.com/tags/SO'>SO</a>
app_extras.py
app_extras.py
import re
register = template.Library()
@register.filter(name='hashchange')
def hashchange(value):
vx=re.findall(r"#(w+)", value)
for n in vx:
pm="<a href='http://example.com/tags/{0}'>{0}</a>".format(n)
return pm
在模板中,我做到了,
{{object.comment|safe|hashchange}}
我错过了什么?
推荐答案
您将需要使用 mark_safe
将您的返回值标记为 html.请记住,由于您将其标记为安全,因此您必须 先转义.re.sub()
正是您要找的:
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)))
注意:我们假设 value
是文本(未转义),而 create_hashtag_link(tag)
假设 tag
是一个单词(w+
) 并且不需要转义.要创建指向其他文本片段的链接,请使用 format_html()
而不是 .format()
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()
这篇关于使用模板标签使模板中的所有主题标签均可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!