[Answer]-Truncate characters in a HTML element – Django Templates

1👍

Wow, that’s a strange requirement. You would have to implement this as a template tag or custom filter that takes a list and transforms it.

@register.filter(name='truncatinator')
def truncatinator(value, arg):
    strings = ",".join(value)
    if len(strings) >= arg:
        part = strings[0:19] + "..."
    return part.split(',')

and use it like this {% for object in job.key_list|truncatinator:"20" %}

What you will notice though is that you will loop over a string list here instead of your objects which will give you this disadvantage: You won’t have access to your .id.
This could be modified though as well.

I would do this with Javascript instead but I don’t think that Django should be responsible for this overall.

Leave a comment