开发者

How to add an ellipsis in a Django template using truncatewords without the final space?

开发者 https://www.devze.com 2023-01-22 23:48 出处:网络
The truncatewords filter inserts a space before the elipsis. As in, \'A fine holiday recipe book of ...\'

The truncatewords filter inserts a space before the elipsis. As in, 'A fine holiday recipe book of ...'

vs. the desired

'A fine holiday recipe book of...'

Is there an easy way to get this filter to not put a space there? I could take care of this in the view pretty easily, b开发者_高级运维ut would prefer to do it in the template - ideally without creating a custom filter. Any suggestions are welcome.


There are a bunch of template filters at Djangosnippets, and this one looks pretty neat:

# 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) + '...'


This will also work:

{{ value|truncatewords:3|slice:"-4" }}...

Basically, just slice off the last 4 characters (ellipse plus space), and then add it back without the space!

The neat thing is, with this method you can also end your, uh, truncation with anything you'd like.

0

精彩评论

暂无评论...
验证码 换一张
取 消