我有一个像这样的文本域:
class Comment(models.Model):
...
comment_text = models.TextField(max_length=650, blank=True, null=True)
当有人在 TextField
中发布链接时,例如www.stackoverflow.com ,我希望它是可点击的(嵌套在 <a>
标签中)。有什么方法可以使用代码而不是使用文本编辑器来做到这一点吗?
最佳答案
您可以使用 urlize
[Django-doc]为此的模板过滤器标签。所以不要写:
{{ some_comment.comment_text }}
你应该写:
{{ some_comment.comment_text<b>|urlize</b> }}
根据文档,我们得到:
Converts URLs and email addresses in text into clickable links.
This template tag works on links prefixed with
http://
,https://
, orwww.
. For example,https://goo.gl/aia1t
will get converted butgoo.gl/aia1t
won’t.It also supports domain-only links ending in one of the original top level domains (
.com
,.edu
,.gov
,.int
,.mil
,.net
, and.org
). For example,djangoproject.com
gets converted.(..)
If value is
"Check out www.djangoproject.com"
, the output will be"Check out <a href="http://www.djangoproject.com" rel="nofollow">www.djangoproject.com</a>"
.
相关的模板过滤器是 urlizetrunc
[Django-doc]其中的链接不仅可以点击,而且还可以被 chop 。例如:
{{ some_comment.comment_text<b>|urlizetrunc:15</b> }}
在这种情况下,用户看到的 URL(当然不是链接本身)被 chop 为 15 个字符,因为链接可能非常长且困惑。
关于javascript - 在我的 Django TextField 中使链接可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51243907/