~canonical-django/canonical-django/project-template

« back to all changes in this revision

Viewing changes to trunk/python-packages/django/contrib/webdesign/templatetags/webdesign.py

  • Committer: Matthew Nuzum
  • Date: 2008-11-13 05:46:03 UTC
  • Revision ID: matthew.nuzum@canonical.com-20081113054603-v0kvr6z6xyexvqt3
adding to version control

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
from django.contrib.webdesign.lorem_ipsum import words, paragraphs
 
2
from django import template
 
3
 
 
4
register = template.Library()
 
5
 
 
6
class LoremNode(template.Node):
 
7
    def __init__(self, count, method, common):
 
8
        self.count, self.method, self.common = count, method, common
 
9
 
 
10
    def render(self, context):
 
11
        try:
 
12
            count = int(self.count.resolve(context))
 
13
        except (ValueError, TypeError):
 
14
            count = 1
 
15
        if self.method == 'w':
 
16
            return words(count, common=self.common)
 
17
        else:
 
18
            paras = paragraphs(count, common=self.common)
 
19
        if self.method == 'p':
 
20
            paras = ['<p>%s</p>' % p for p in paras]
 
21
        return u'\n\n'.join(paras)
 
22
 
 
23
#@register.tag
 
24
def lorem(parser, token):
 
25
    """
 
26
    Creates random Latin text useful for providing test data in templates.
 
27
 
 
28
    Usage format::
 
29
 
 
30
        {% lorem [count] [method] [random] %}
 
31
 
 
32
    ``count`` is a number (or variable) containing the number of paragraphs or
 
33
    words to generate (default is 1).
 
34
 
 
35
    ``method`` is either ``w`` for words, ``p`` for HTML paragraphs, ``b`` for
 
36
    plain-text paragraph blocks (default is ``b``).
 
37
 
 
38
    ``random`` is the word ``random``, which if given, does not use the common
 
39
    paragraph (starting "Lorem ipsum dolor sit amet, consectetuer...").
 
40
 
 
41
    Examples:
 
42
        * ``{% lorem %}`` will output the common "lorem ipsum" paragraph
 
43
        * ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph
 
44
          and two random paragraphs each wrapped in HTML ``<p>`` tags
 
45
        * ``{% lorem 2 w random %}`` will output two random latin words
 
46
    """
 
47
    bits = list(token.split_contents())
 
48
    tagname = bits[0]
 
49
    # Random bit
 
50
    common = bits[-1] != 'random'
 
51
    if not common:
 
52
        bits.pop()
 
53
    # Method bit
 
54
    if bits[-1] in ('w', 'p', 'b'):
 
55
        method = bits.pop()
 
56
    else:
 
57
        method = 'b'
 
58
    # Count bit
 
59
    if len(bits) > 1:
 
60
        count = bits.pop()
 
61
    else:
 
62
        count = '1'
 
63
    count = parser.compile_filter(count)
 
64
    if len(bits) != 1:
 
65
        raise template.TemplateSyntaxError("Incorrect format for %r tag" % tagname)
 
66
    return LoremNode(count, method, common)
 
67
lorem = register.tag(lorem)