Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 385
JAL Avatar asked Nov 02 '10 21:11

JAL


2 Answers

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) + '...'
like image 59
Steve Jalim Avatar answered Oct 21 '22 15:10

Steve Jalim


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.

like image 28
Ben Hodes Avatar answered Oct 21 '22 16:10

Ben Hodes