Code

Ticket #4655: truncatewords.2.patch

File truncatewords.2.patch, 1.7 KB (added by SmileyChris, 7 years ago)
  • 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    words = [] 
     38    for count, match in enumerate(re.finditer(r'(?:^\s+)?\S+\s*', s)): 
     39        if count >= length:   # count is 0-based 
     40            if words: 
     41                last_word = words[-1].rstrip() 
     42                words[-1] = last_word 
     43                if not last_word.endswith('...'): 
     44                    words.append(' ...') 
     45            break 
     46        words.append(match.group()) 
     47    return ''.join(words) 
    4348 
    4449def truncate_html_words(s, num): 
    4550    """ 
  • tests/regressiontests/defaultfilters/tests.py

     
    8989>>> truncatewords('A sentence with a few words in it', 'not a number') 
    9090'A sentence with a few words in it' 
    9191 
     92# truncatewords should preserve whitespace, as it may be useful for 
     93# chained filters (such as linebreaks) 
     94>>> truncatewords('   Three \n   words\n    still\t', 2) 
     95'   Three \n   words ...' 
     96>>> truncatewords('   Three \n   words\n    still\t', 3) 
     97'   Three \n   words\n    still\t' 
     98 
    9299>>> truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 0) 
    93100'' 
    94101