如何使用truncatewords在没有最终空格的Django模板中添加省略号?

JAL*_*JAL 5 django templates truncate trim

truncatewords过滤器在省略号之前插入一个空格.就像在'一个精美的节日食谱书......'
与期望的
'一个精美的节日食谱书......'

有没有一种简单的方法可以让这个过滤器不在那里放置空间?我可以很容易地在视图中处理这个问题,但更愿意在模板中进行 - 最好不要创建自定义过滤器.欢迎任何建议.

Ste*_*lim 6

Djangosnippets有一堆模板过滤器,这个看起来非常整洁:

# From http://djangosnippets.org/snippets/1259/

from django import template

register = template.Library()

@register.filter
def truncatesmart(value, limit=80):
    """
    Truncates a string after a given number of chars keeping whole words.

    Usage:
        {{ string|truncatesmart }}
        {{ string|truncatesmart:50 }}
    """

    try:
        limit = int(limit)
    # invalid literal for int()
    except ValueError:
        # Fail silently.
        return value

    # Make sure it's unicode
    value = unicode(value)

    # Return the string itself if length is smaller or equal to the limit
    if len(value) <= limit:
        return value

    # Cut the string
    value = value[:limit]

    # Break into words and remove the last
    words = value.split(' ')[:-1]

    # Join the words and return
    return ' '.join(words) + '...'
Run Code Online (Sandbox Code Playgroud)