from django import template from string import replace register = template.Library() @register.filter def truncatechars(value, limit=90): try: limit = int(limit) except ValueError: return value value = unicode(value) # Retorna a string normal caso ela seja menor que o limite if len(value) <= limit: return value # Corta a string conforme o numero passado no limit value = value[:limit] # Separa a string words = value.split(' ')[:-1] # Acrescenta '...' a string cortada e retorna ela para o template return ' '.join(words) + '...'