在带有Templatetags的模板中使所有主题标签可单击 [英] Make All hashtags clickable in Template with Templatetags
问题描述
我想将注释
文本字段中的每个主题标签都变为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}.
我尝试了以下templatetags代码,但它赢得了不返回带有文本的主题标签。只会返回此值,
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()
这篇关于在带有Templatetags的模板中使所有主题标签可单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!