Ticket #4655: truncatewords.patch
File truncatewords.patch, 1.7 KB (added by , 17 years ago) |
---|
-
django/utils/text.py
34 34 def truncate_words(s, num): 35 35 "Truncates a string after a certain number of words." 36 36 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: 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) 43 48 44 49 def truncate_html_words(s, num): 45 50 """ -
tests/regressiontests/defaultfilters/tests.py
89 89 >>> truncatewords('A sentence with a few words in it', 'not a number') 90 90 'A sentence with a few words in it' 91 91 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 92 99 >>> truncatewords_html('<p>one <a href="#">two - three <br>four</a> five</p>', 0) 93 100 '' 94 101