代码之家  ›  专栏  ›  技术社区  ›  thumbtackthief

在Django模板标记中包含URL

  •  0
  • thumbtackthief  · 技术社区  · 13 年前

    我正在构建一个Django博客应用程序,因为这显然是所有酷孩子都在做的事情。我已经构建了一个模板标签,如果帖子很长,只显示帖子的开头,理想情况下包括整个帖子的链接。我开始研究escape和IsSafe=True,但我担心内容本身可能有HTML标记,这可能会把事情搞砸。

    以下是我现在拥有的:

    @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 回复  |  直到 13 年前
        1
  •  1
  •   catherine    13 年前
    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)