2013-04-04 71 views
0

我正在构建一个Django博客应用程序,因为这显然是所有酷炫的孩子正在做的事情。我已经构建了一个模板标签,以便只显示帖子的开头,如果它很长,并且最好包含整个帖子的链接。我开始考虑转义并且IsSafe = True,但是我担心内容本身可能包含HTML标签,可能会导致混乱。在Django模板标签中包含一个URL

这是我现在有:

@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 

回答

1
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) 
+0

嗯...显然越来越近。我纠正它应该是(注意引号): 'output =“{0} ... (cont.)”.format(content [:500])' – thumbtackthief 2013-04-05 20:46:16

+0

不改变引号,我得到一个语法错误。有了它,它会重定向到/entry/%7bpost.id%7d。 – thumbtackthief 2013-04-05 20:47:02

+0

你需要通过有效的'post.id' – catherine 2013-04-06 02:32:38

相关问题