Ticket #4655: truncate_words.2.patch

File truncate_words.2.patch, 1004 bytes (added by colin@…, 17 years ago)

Updated with a fix for single line short text.

  • django/utils/text.py

     
    3434def truncate_words(s, num):
    3535    "Truncates a string after a certain number of words."
    3636    length = int(num)
    37     words = s.split()
    38     if len(words) > length:
    39         words = words[:length]
    40         if not words[-1].endswith('...'):
    41             words.append('...')
    42     return ' '.join(words)
     37    lines = s.splitlines (True)
     38    result = []
     39    count = 0
     40    for line in lines:
     41        words = line.split()
     42        senLen = len (words)
     43        if (count + senLen > length):
     44            result.extend (words[0:(length - count)])
     45            if not result[-1].endswith('...'):
     46                result.append('...')
     47                return ' '.join (result)
     48        result.append (line)
     49        count = count + senLen
     50    return ' '.join (result)
    4351
    4452def truncate_html_words(s, num):
    4553    """
Back to Top