Login

Truncate words by characters

Author:
trodrigues
Posted:
May 19, 2008
Language:
Python
Version:
.96
Tags:
filter truncate character word
Score:
1 (after 1 ratings)

This filter truncates words like the original truncate words Django filter, but instead of being based on the number of words, it's based on the number of characters. I found the need for this when building a website where i'd have to show labels on really small text boxes and truncating by words didn't always gave me the best results (and truncating by character is...well...not that elegant).

Usage example: {{var|truncatewords_by_chars:"16 2 4"}}

If string lenght is higher than 16, truncates by 2 words, if lesser, truncates by 4 words.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django import template

register = template.Library()

@register.filter
def truncatewords_by_chars(value, arg):
  """
  Truncate words based on the number of characters
  based on original truncatewords filter code
  
  Receives a parameter separated by spaces where each field means:
   - limit: number of characters after which the string is truncated
   - lower bound: if char number is higher than limit, truncate by lower bound
   - higher bound: if char number is less than limit, truncate by higher bound
  """
  from django.utils.text import truncate_words
  try:
    args = arg.split(' ')
    limit = int(args[0])
    lower = int(args[1])
    higher = int(args[2])
  except ValueError: # Invalid literal for int().
    return value
  if len(value) >= limit:
    return truncate_words(value, lower)
  if len(value) < limit:
    return truncate_words(value, higher)

More like this

  1. truncatehtml_at_word by zakj 6 years, 7 months ago
  2. Truncate filter by zalun 6 years, 2 months ago
  3. Truncate string after a given number of chars keeping whole words by rix 6 years, 6 months ago
  4. Precise truncate chars filter by davmuz 3 years, 5 months ago
  5. Truncate Characters Filter (simple) by leahculver 8 years, 2 months ago

Comments

Please login first before commenting.