Ticket #1919: truncate_words.diff
File truncate_words.diff, 1.8 KB (added by , 17 years ago) |
---|
-
django/utils/text.py
36 36 return u''.join(_generator()) 37 37 wrap = allow_lazy(wrap, unicode) 38 38 39 word_re = re.compile(r'\S+', re.UNICODE) 39 40 def truncate_words(s, num): 40 41 "Truncates a string after a certain number of words." 41 42 s = force_unicode(s) 42 43 length = int(num) 43 words = s.split() 44 if len(words) > length: 45 words = words[:length] 46 if not words[-1].endswith('...'): 47 words.append('...') 48 return u' '.join(words) 44 if length < 1: 45 return u'' 46 for count, match in enumerate(word_re.finditer(s)): 47 if count + 1 == length: # count is 0-based 48 end = match.end() 49 if end < len(s): 50 s = s[:end] 51 if not s.endswith('...'): 52 s += ' ...' 53 break 54 return s 49 55 truncate_words = allow_lazy(truncate_words, unicode) 50 56 51 57 def truncate_html_words(s, num): -
tests/regressiontests/defaultfilters/tests.py
98 98 >>> truncatewords(u'A sentence with a few words in it', 'not a number') 99 99 u'A sentence with a few words in it' 100 100 101 >>> truncatewords(u'Double-spaced sentence with a few words', 2) 102 u'Double-spaced sentence ...' 103 104 >>> truncatewords(u' Two leading spaces for this sentence', 3) 105 u' Two leading spaces ...' 106 107 >>> truncatewords(u'Some text\non two lines', 4) 108 u'Some text\non two ...' 109 101 110 >>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 0) 102 111 u'' 103 112