Python 在Django模板标记中包含URL
我正在构建一个Django博客应用程序,因为这显然是所有酷孩子都在做的事情。我已经构建了一个模板标签,如果文章很长,它只显示文章的开头,理想的情况是包含一个指向整个文章的链接。我开始研究转义和IsSafe=True,但我担心的是内容本身可能有HTML标记,这可能会把事情搞砸 以下是我现在拥有的:Python 在Django模板标记中包含URL,python,html,django,Python,Html,Django,我正在构建一个Django博客应用程序,因为这显然是所有酷孩子都在做的事情。我已经构建了一个模板标签,如果文章很长,它只显示文章的开头,理想的情况是包含一个指向整个文章的链接。我开始研究转义和IsSafe=True,但我担心的是内容本身可能有HTML标记,这可能会把事情搞砸 以下是我现在拥有的: @register.filter(name='shorten') def shorten(content): #will show up to the first 500 characters
@register.filter(name='shorten')
def shorten(content):
#will show up to the first 500 characters of the post content
if len(content) > 500:
return content[:500] + '...' + <a href="/entry/{{post.id}}">(cont.)</a>
else:
return content
@register.filter(name='shorten')
def(内容):
#将最多显示帖子内容的前500个字符
如果长度(含量)>500:
返回内容[:500]+'…'+
其他:
返回内容
来自django.utils.safestring导入标记\u safe
@register.filter(name='shorten')
def缩短(内容、发布id):
#将最多显示帖子内容的前500个字符
如果长度(含量)>500:
output=“{0}…”格式(内容[:500],post_id)
其他:
output=“{0}”。格式(内容)
返回标记_安全(输出)
Hmm。。。显然越来越近了。我是否正确(注意引号):output=“{0}…”格式(content[:500])
如果不更改引号,我会得到一个语法错误。有了它,它会重定向到/entry/%7post.id%7d。你需要传递有效的post.id
好的。我修改了我的答案,以便你能理解。谢谢。我不熟悉{0}语法;你能告诉我那叫什么吗?这样我就可以查到它并学习它了?看起来很有用。
from django.utils.safestring import mark_safe
@register.filter(name='shorten')
def shorten(content, post_id):
#will show up to the first 500 characters of the post content
if len(content) > 500:
output = "{0}... <a href='/entry/{1}'>(cont.)</a>".format(content[:500], post_id)
else:
output = "{0}".format(content)
return mark_safe(output)