Django template tag to truncate text

Django has truncatewords template tag, which cuts the text at the given word count. But there is nothing like truncatechars.

What's the best way to cut the text in the template at given char-length limit?


This has recently been added in Django 1.4. e.g.:

{{ value|truncatechars:9 }}

See doc here


{{ value|slice:"5" }}{% if value|length > 5 %}...{% endif %}

Update

Since version 1.4, Django have a built-in template tag for this:

{{ value|truncatechars:9 }}

I made my own template filter, that add "..." to the end of (last word of) the (truncated) string as well:

from django import template
register = template.Library()

@register.filter("truncate_chars")
def truncate_chars(value, max_length):
    if len(value) > max_length:
        truncd_val = value[:max_length]
        if not len(value) == max_length+1 and value[max_length+1] != " ":
            truncd_val = truncd_val[:truncd_val.rfind(" ")]
        return  truncd_val + "..."
    return value