JAL
JAL

Reputation: 21563

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

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, but would prefer to do it in the template - ideally without creating a custom filter. Any suggestions are welcome.

Upvotes: 5

Views: 8031

Answers (2)

Steve Jalim
Steve Jalim

Reputation: 12195

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

Upvotes: 7

Ben Hodes
Ben Hodes

Reputation: 63

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.

Upvotes: 3

Related Questions