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.

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

Need Your Help

Load XML for each request

java xml java-ee

My application loads a xml and update xml elements for each request.

Mysql query to select from where value is X% less or X% more than a value

php mysql

What im trying to accomplish is to select all the users who has 20% more or 20% less than $influencer_account['followed_by'].

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.