Ticket #3799: lorem_ipsum.patch

File lorem_ipsum.patch, 10.4 KB (added by Chris Beaven, 17 years ago)

with tests and docs

  • django/template/defaulttags.py

     
    280280    def render(self, context):
    281281        return ''
    282282
     283class LoremNode(Node):
     284    def __init__(self, count, method, common):
     285        self.count, self.method, self.common = count, method, common
     286
     287    def render(self, context):
     288        from django.utils.lorem_ipsum import words, paragraphs
     289        try:
     290            count = int(self.count.resolve(context))
     291        except (ValueError, TypeError):
     292            count = 1
     293        if self.method == 'w':
     294            return words(count, common=self.common)
     295        else:
     296            paras = paragraphs(count, common=self.common)
     297        if self.method == 'p':
     298            paras = ['<p>%s</p>' % p for p in paras]
     299        return '\n\n'.join(paras)
     300
    283301class NowNode(Node):
    284302    def __init__(self, format_string):
    285303        self.format_string = format_string
     
    769787load = register.tag(load)
    770788
    771789#@register.tag
     790def lorem(parser, token):
     791    """
     792    Creates random latin text useful for providing test data in templates.
     793
     794    Usage format::
     795
     796        {% lorem [count] [method] [random] %}
     797
     798    ``count`` is a number (or variable) containing the number of paragraphs or
     799    words to generate (default is 1).
     800
     801    ``method`` is either ``w`` for words, ``p`` for HTML paragraphs, ``b`` for
     802    plain-text paragraph blocks (default is ``b``).
     803
     804    ``random`` is the word ``random``, which if given, does not use the common
     805    paragraph (starting "Lorem ipsum dolor sit amet, consectetuer...").
     806
     807    Examples:
     808        * ``{% lorem %}`` will output the common "lorem ipsum" paragraph
     809        * ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph
     810          and two random paragraphs each wrapped in HTML ``<p>`` tags
     811        * ``{% lorem 2 w random %}`` will output two random latin words
     812    """
     813    bits = list(token.split_contents())
     814    tagname = bits[0]
     815    # Random bit
     816    common = bits[-1] != 'random'
     817    if not common:
     818        bits.pop()
     819    # Method bit
     820    if bits[-1] in ('w', 'p', 'b'):
     821        method = bits.pop()
     822    else:
     823        method = 'b'
     824    # Count bit
     825    if len(bits) > 1:
     826        count = bits.pop()
     827    else:
     828        count = '1'
     829    count = parser.compile_filter(count)
     830    if len(bits) != 1:
     831        raise TemplateSyntaxError, "Incorrect format for %r tag" % tagname
     832    return LoremNode(count, method, common)
     833lorem = register.tag(lorem)   
     834
     835#@register.tag
    772836def now(parser, token):
    773837    """
    774838    Display the date, formatted according to the given string.
  • django/utils/lorem_ipsum.py

     
     1import random
     2
     3COMMON_P = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
     4WORDS = ('exercitationem', 'perferendis', 'perspiciatis', 'laborum', 'eveniet', 'sunt', 'iure', 'nam', 'nobis', 'eum', 'cum', 'officiis', 'excepturi', 'odio', 'consectetur', 'quasi', 'aut', 'quisquam', 'vel', 'eligendi', 'itaque', 'non', 'odit', 'tempore', 'quaerat', 'dignissimos', 'facilis', 'neque', 'nihil', 'expedita', 'vitae', 'vero', 'ipsum', 'nisi', 'animi', 'cumque', 'pariatur', 'velit', 'modi', 'natus', 'iusto', 'eaque', 'sequi', 'illo', 'sed', 'ex', 'et', 'voluptatibus', 'tempora', 'veritatis', 'ratione', 'assumenda', 'incidunt', 'nostrum', 'placeat', 'aliquid', 'fuga', 'provident', 'praesentium', 'rem', 'necessitatibus', 'suscipit', 'adipisci', 'quidem', 'possimus', 'voluptas', 'debitis', 'sint', 'accusantium', 'unde', 'sapiente', 'voluptate', 'qui', 'aspernatur', 'laudantium', 'soluta', 'amet', 'quo', 'aliquam', 'saepe', 'culpa', 'libero', 'ipsa', 'dicta', 'reiciendis', 'nesciunt', 'doloribus', 'autem', 'impedit', 'minima', 'maiores', 'repudiandae', 'ipsam', 'obcaecati', 'ullam', 'enim', 'totam', 'delectus', 'ducimus', 'quis', 'voluptates', 'dolores', 'molestiae', 'harum', 'dolorem', 'quia', 'voluptatem', 'molestias', 'magni', 'distinctio', 'omnis', 'illum', 'dolorum', 'voluptatum', 'ea', 'quas', 'quam', 'corporis', 'quae', 'blanditiis', 'atque', 'deserunt', 'laboriosam', 'earum', 'consequuntur', 'hic', 'cupiditate', 'quibusdam', 'accusamus', 'ut', 'rerum', 'error', 'minus', 'eius', 'ab', 'ad', 'nemo', 'fugit', 'officia', 'at', 'in', 'id', 'quos', 'reprehenderit', 'numquam', 'iste', 'fugiat', 'sit', 'inventore', 'beatae', 'repellendus', 'magnam', 'recusandae', 'quod', 'explicabo', 'doloremque', 'aperiam', 'consequatur', 'asperiores', 'commodi', 'optio', 'dolor', 'labore', 'temporibus', 'repellat', 'veniam', 'architecto', 'est', 'esse', 'mollitia', 'nulla', 'a', 'similique', 'eos', 'alias', 'dolore', 'tenetur', 'deleniti', 'porro', 'facere', 'maxime', 'corrupti')
     5COMMON_WORDS = ('lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua')
     6
     7def sentence():
     8    sentence = []
     9    # Determine the number of comma separated sections and number of words in
     10    # each section for this sentence.
     11    section_count = random.randint(1, 5)
     12    section_max_length = 12 - section_count
     13    section_lengths = []
     14    length = 0
     15    for i in range(section_count):
     16        section_length = random.randint(3, section_max_length)
     17        length += section_length
     18        section_lengths.append(section_length)
     19    # Fill each comma seperated section from the sample of latin words.
     20    words = random.sample(WORDS, length)
     21    for section_length in section_lengths:
     22        section = []
     23        for i in range(section_length):
     24            section.append(words.pop())
     25        sentence.append(' '.join(section))
     26    sentence = ', '.join(sentence)
     27    # Convert to sentence case and add end punctuation.
     28    sentence = '%s%s%s' % (sentence[0].upper(), sentence[1:], random.choice('?.'))
     29    return sentence
     30
     31def paragraph():
     32    paragraph = []
     33    for i in range(random.randint(1, 4)):
     34        paragraph.append(sentence())
     35    return ' '.join(paragraph)
     36
     37def paragraphs(count, common=True):
     38    paragraphs = []
     39    for i in range(count):
     40        if i == 0 and common:
     41            paragraphs.append(COMMON_P)
     42        else:
     43            paragraphs.append(paragraph())
     44    return paragraphs
     45
     46def words(count, common=True):
     47    if common:
     48        words = list(COMMON_WORDS)
     49    else:
     50        words = []
     51    c = len(words)
     52    if count > c:
     53        count = min(count - c, len(WORDS))
     54        words += random.sample(WORDS, count - c)
     55    else:
     56        words = words[:count]
     57    return ' '.join(words)
     58
  • docs/templates.txt

     
    625625
    626626See `Custom tag and filter libraries`_ for more information.
    627627
     628lorem
     629~~~~~
     630
     631Display random latin text useful for providing test data in templates.
     632
     633Usage format: ``{% lorem [count] [method] [random] %}``
     634
     635    ===========  =============================================================
     636    Argument     Description
     637    ===========  =============================================================
     638    ``count``    A number (or variable) containing the number of paragraphs or
     639                 words to generate (default is 1).
     640    ``method``   Either ``w`` for words, ``p`` for HTML paragraphs or ``b``
     641                 for plain-text paragraph blocks (default is ``b``).
     642    ``random``   The word ``random``, which if given, does not use the common
     643                 paragraph ("Lorem ipsum dolor sit amet...") when generating
     644                 text.
     645
     646Examples:
     647
     648    * ``{% lorem %}`` will output the common "lorem ipsum" paragraph.
     649    * ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph
     650      and two random paragraphs each wrapped in HTML ``<p>`` tags.
     651    * ``{% lorem 2 w random %}`` will output two random latin words.
     652
    628653now
    629654~~~
    630655
  • tests/regressiontests/templates/tests.py

     
    654654            'with01': ('{% with dict.key as key %}{{ key }}{% endwith %}', {'dict': {'key':50}}, '50'),
    655655            'with02': ('{{ key }}{% with dict.key as key %}{{ key }}-{{ dict.key }}-{{ key }}{% endwith %}{{ key }}', {'dict': {'key':50}}, ('50-50-50', 'INVALID50-50-50INVALID')),
    656656
     657            ### LOREM TAG ######################################################
     658            'lorem01': ('{% lorem %}', {}, 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'),
     659            'lorem02': ('{% lorem p %}', {}, '<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>'),
     660            'lorem03': ('{% lorem 6 w %}', {}, 'lorem ipsum dolor sit amet consectetur'),
     661
    657662            ### NOW TAG ########################################################
    658663            # Simple case
    659664            'now01' : ('{% now "j n Y"%}', {}, str(datetime.now().day) + ' ' + str(datetime.now().month) + ' ' + str(datetime.now().year)),
Back to Top