Ticket #1919: truncate_words.diff

File truncate_words.diff, 1.8 KB (added by arien <regexbot@…>, 7 years ago)

truncate_words that does what it says on the package; includes tests

  • django/utils/text.py

     
    3636    return u''.join(_generator())
    3737wrap = allow_lazy(wrap, unicode)
    3838
     39word_re = re.compile(r'\S+', re.UNICODE)
    3940def truncate_words(s, num):
    4041    "Truncates a string after a certain number of words."
    4142    s = force_unicode(s)
    4243    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
    4955truncate_words = allow_lazy(truncate_words, unicode)
    5056
    5157def truncate_html_words(s, num):
  • tests/regressiontests/defaultfilters/tests.py

     
    9898>>> truncatewords(u'A sentence with a few words in it', 'not a number')
    9999u'A sentence with a few words in it'
    100100
     101>>> truncatewords(u'Double-spaced  sentence  with  a  few  words', 2)
     102u'Double-spaced  sentence ...'
     103
     104>>> truncatewords(u'  Two leading spaces for this sentence', 3)
     105u'  Two leading spaces ...'
     106
     107>>> truncatewords(u'Some text\non two lines', 4)
     108u'Some text\non two ...'
     109
    101110>>> truncatewords_html(u'<p>one <a href="#">two - three <br>four</a> five</p>', 0)
    102111u''
    103112
Back to Top