Django template tag to truncate text

{{ 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

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

{{ value|truncatechars:9 }}

See doc here