Fixed #3799 -- Added django.contrib.webdesign and moved 'lorem' template tag into there
git-svn-id: http://code.djangoproject.com/svn/django/trunk@4857 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
parent
587abaa95c
commit
d22e39c10d
|
@ -0,0 +1,66 @@
|
|||
"""
|
||||
Utility functions for generating "lorem ipsum" Latin text.
|
||||
"""
|
||||
|
||||
import random
|
||||
|
||||
COMMON_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.'
|
||||
WORDS = ('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')
|
||||
COMMON_WORDS = ('lorem', 'ipsum', 'dolor', 'sit', 'amet', 'consectetur', 'adipisicing', 'elit', 'sed', 'do', 'eiusmod', 'tempor', 'incididunt', 'ut', 'labore', 'et', 'dolore', 'magna', 'aliqua')
|
||||
|
||||
def sentence():
|
||||
"""
|
||||
Returns a randomly generated sentence of lorem ipsum text.
|
||||
|
||||
The first word is capitalized, and the sentence ends in either a period or
|
||||
question mark. Commas are added at random.
|
||||
"""
|
||||
# Determine the number of comma-separated sections and number of words in
|
||||
# each section for this sentence.
|
||||
sections = [' '.join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5))]
|
||||
s = ', '.join(sections)
|
||||
# Convert to sentence case and add end punctuation.
|
||||
return '%s%s%s' % (s[0].upper(), s[1:], random.choice('?.'))
|
||||
|
||||
def paragraph():
|
||||
"""
|
||||
Returns a randomly generated paragraph of lorem ipsum text.
|
||||
|
||||
The paragraph consists of between 1 and 4 sentences, inclusive.
|
||||
"""
|
||||
return ' '.join([sentence() for i in range(random.randint(1, 4))])
|
||||
|
||||
def paragraphs(count, common=True):
|
||||
"""
|
||||
Returns a list of paragraphs as returned by paragraph().
|
||||
|
||||
If `common` is True, then the first paragraph will be the standard
|
||||
'lorem ipsum' paragraph. Otherwise, the first paragraph will be random
|
||||
Latin text. Either way, subsequent paragraphs will be random Latin text.
|
||||
"""
|
||||
paras = []
|
||||
for i in range(count):
|
||||
if common and i == 0:
|
||||
paras.append(COMMON_P)
|
||||
else:
|
||||
paras.append(paragraph())
|
||||
return paras
|
||||
|
||||
def words(count, common=True):
|
||||
"""
|
||||
Returns a string of `count` lorem ipsum words separated by a single space.
|
||||
|
||||
If `common` is True, then the first 19 words will be the standard
|
||||
'lorem ipsum' words. Otherwise, all words will be selected randomly.
|
||||
"""
|
||||
if common:
|
||||
word_list = list(COMMON_WORDS)
|
||||
else:
|
||||
word_list = []
|
||||
c = len(word_list)
|
||||
if count > c:
|
||||
count = min(count - c, len(WORDS))
|
||||
word_list += random.sample(WORDS, count - c)
|
||||
else:
|
||||
word_list = word_list[:count]
|
||||
return ' '.join(word_list)
|
|
@ -0,0 +1,67 @@
|
|||
from django.contrib.webdesign.lorem_ipsum import words, paragraphs
|
||||
from django import template
|
||||
|
||||
register = template.Library()
|
||||
|
||||
class LoremNode(template.Node):
|
||||
def __init__(self, count, method, common):
|
||||
self.count, self.method, self.common = count, method, common
|
||||
|
||||
def render(self, context):
|
||||
try:
|
||||
count = int(self.count.resolve(context))
|
||||
except (ValueError, TypeError):
|
||||
count = 1
|
||||
if self.method == 'w':
|
||||
return words(count, common=self.common)
|
||||
else:
|
||||
paras = paragraphs(count, common=self.common)
|
||||
if self.method == 'p':
|
||||
paras = ['<p>%s</p>' % p for p in paras]
|
||||
return '\n\n'.join(paras)
|
||||
|
||||
#@register.tag
|
||||
def lorem(parser, token):
|
||||
"""
|
||||
Creates random Latin text useful for providing test data in templates.
|
||||
|
||||
Usage format::
|
||||
|
||||
{% lorem [count] [method] [random] %}
|
||||
|
||||
``count`` is a number (or variable) containing the number of paragraphs or
|
||||
words to generate (default is 1).
|
||||
|
||||
``method`` is either ``w`` for words, ``p`` for HTML paragraphs, ``b`` for
|
||||
plain-text paragraph blocks (default is ``b``).
|
||||
|
||||
``random`` is the word ``random``, which if given, does not use the common
|
||||
paragraph (starting "Lorem ipsum dolor sit amet, consectetuer...").
|
||||
|
||||
Examples:
|
||||
* ``{% lorem %}`` will output the common "lorem ipsum" paragraph
|
||||
* ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph
|
||||
and two random paragraphs each wrapped in HTML ``<p>`` tags
|
||||
* ``{% lorem 2 w random %}`` will output two random latin words
|
||||
"""
|
||||
bits = list(token.split_contents())
|
||||
tagname = bits[0]
|
||||
# Random bit
|
||||
common = bits[-1] != 'random'
|
||||
if not common:
|
||||
bits.pop()
|
||||
# Method bit
|
||||
if bits[-1] in ('w', 'p', 'b'):
|
||||
method = bits.pop()
|
||||
else:
|
||||
method = 'b'
|
||||
# Count bit
|
||||
if len(bits) > 1:
|
||||
count = bits.pop()
|
||||
else:
|
||||
count = '1'
|
||||
count = parser.compile_filter(count)
|
||||
if len(bits) != 1:
|
||||
raise TemplateSyntaxError("Incorrect format for %r tag" % tagname)
|
||||
return LoremNode(count, method, common)
|
||||
lorem = register.tag(lorem)
|
|
@ -140,7 +140,7 @@ class IfChangedNode(Node):
|
|||
else:
|
||||
compare_to = self.nodelist.render(context)
|
||||
except VariableDoesNotExist:
|
||||
compare_to = None
|
||||
compare_to = None
|
||||
|
||||
if compare_to != self._last_seen:
|
||||
firstloop = (self._last_seen == None)
|
||||
|
@ -280,24 +280,6 @@ class LoadNode(Node):
|
|||
def render(self, context):
|
||||
return ''
|
||||
|
||||
class LoremNode(Node):
|
||||
def __init__(self, count, method, common):
|
||||
self.count, self.method, self.common = count, method, common
|
||||
|
||||
def render(self, context):
|
||||
from django.utils.lorem_ipsum import words, paragraphs
|
||||
try:
|
||||
count = int(self.count.resolve(context))
|
||||
except (ValueError, TypeError):
|
||||
count = 1
|
||||
if self.method == 'w':
|
||||
return words(count, common=self.common)
|
||||
else:
|
||||
paras = paragraphs(count, common=self.common)
|
||||
if self.method == 'p':
|
||||
paras = ['<p>%s</p>' % p for p in paras]
|
||||
return '\n\n'.join(paras)
|
||||
|
||||
class NowNode(Node):
|
||||
def __init__(self, format_string):
|
||||
self.format_string = format_string
|
||||
|
@ -338,7 +320,7 @@ class URLNode(Node):
|
|||
self.view_name = view_name
|
||||
self.args = args
|
||||
self.kwargs = kwargs
|
||||
|
||||
|
||||
def render(self, context):
|
||||
from django.core.urlresolvers import reverse, NoReverseMatch
|
||||
args = [arg.resolve(context) for arg in self.args]
|
||||
|
@ -786,52 +768,6 @@ def load(parser, token):
|
|||
return LoadNode()
|
||||
load = register.tag(load)
|
||||
|
||||
#@register.tag
|
||||
def lorem(parser, token):
|
||||
"""
|
||||
Creates random latin text useful for providing test data in templates.
|
||||
|
||||
Usage format::
|
||||
|
||||
{% lorem [count] [method] [random] %}
|
||||
|
||||
``count`` is a number (or variable) containing the number of paragraphs or
|
||||
words to generate (default is 1).
|
||||
|
||||
``method`` is either ``w`` for words, ``p`` for HTML paragraphs, ``b`` for
|
||||
plain-text paragraph blocks (default is ``b``).
|
||||
|
||||
``random`` is the word ``random``, which if given, does not use the common
|
||||
paragraph (starting "Lorem ipsum dolor sit amet, consectetuer...").
|
||||
|
||||
Examples:
|
||||
* ``{% lorem %}`` will output the common "lorem ipsum" paragraph
|
||||
* ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph
|
||||
and two random paragraphs each wrapped in HTML ``<p>`` tags
|
||||
* ``{% lorem 2 w random %}`` will output two random latin words
|
||||
"""
|
||||
bits = list(token.split_contents())
|
||||
tagname = bits[0]
|
||||
# Random bit
|
||||
common = bits[-1] != 'random'
|
||||
if not common:
|
||||
bits.pop()
|
||||
# Method bit
|
||||
if bits[-1] in ('w', 'p', 'b'):
|
||||
method = bits.pop()
|
||||
else:
|
||||
method = 'b'
|
||||
# Count bit
|
||||
if len(bits) > 1:
|
||||
count = bits.pop()
|
||||
else:
|
||||
count = '1'
|
||||
count = parser.compile_filter(count)
|
||||
if len(bits) != 1:
|
||||
raise TemplateSyntaxError, "Incorrect format for %r tag" % tagname
|
||||
return LoremNode(count, method, common)
|
||||
lorem = register.tag(lorem)
|
||||
|
||||
#@register.tag
|
||||
def now(parser, token):
|
||||
"""
|
||||
|
@ -980,12 +916,12 @@ templatetag = register.tag(templatetag)
|
|||
|
||||
def url(parser, token):
|
||||
"""
|
||||
Returns an absolute URL matching given view with its parameters.
|
||||
|
||||
Returns an absolute URL matching given view with its parameters.
|
||||
|
||||
This is a way to define links that aren't tied to a particular URL configuration::
|
||||
|
||||
|
||||
{% url path.to.some_view arg1,arg2,name1=value1 %}
|
||||
|
||||
|
||||
The first argument is a path to a view. It can be an absolute python path
|
||||
or just ``app_name.view_name`` without the project name if the view is
|
||||
located inside the project. Other arguments are comma-separated values
|
||||
|
@ -994,18 +930,18 @@ def url(parser, token):
|
|||
|
||||
For example if you have a view ``app_name.client`` taking client's id and
|
||||
the corresponding line in a URLconf looks like this::
|
||||
|
||||
|
||||
('^client/(\d+)/$', 'app_name.client')
|
||||
|
||||
|
||||
and this app's URLconf is included into the project's URLconf under some
|
||||
path::
|
||||
|
||||
|
||||
('^clients/', include('project_name.app_name.urls'))
|
||||
|
||||
|
||||
then in a template you can create a link for a certain client like this::
|
||||
|
||||
|
||||
{% url app_name.client client.id %}
|
||||
|
||||
|
||||
The URL will look like ``/clients/client/123/``.
|
||||
"""
|
||||
bits = token.contents.split(' ', 2)
|
||||
|
|
|
@ -625,31 +625,6 @@ Load a custom template tag set.
|
|||
|
||||
See `Custom tag and filter libraries`_ for more information.
|
||||
|
||||
lorem
|
||||
~~~~~
|
||||
|
||||
Display random latin text useful for providing sample data in templates.
|
||||
|
||||
Usage format: ``{% lorem [count] [method] [random] %}``
|
||||
|
||||
=========== =============================================================
|
||||
Argument Description
|
||||
=========== =============================================================
|
||||
``count`` A number (or variable) containing the number of paragraphs or
|
||||
words to generate (default is 1).
|
||||
``method`` Either ``w`` for words, ``p`` for HTML paragraphs or ``b``
|
||||
for plain-text paragraph blocks (default is ``b``).
|
||||
``random`` The word ``random``, which if given, does not use the common
|
||||
paragraph ("Lorem ipsum dolor sit amet...") when generating
|
||||
text.
|
||||
|
||||
Examples:
|
||||
|
||||
* ``{% lorem %}`` will output the common "lorem ipsum" paragraph.
|
||||
* ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph
|
||||
and two random paragraphs each wrapped in HTML ``<p>`` tags.
|
||||
* ``{% lorem 2 w random %}`` will output two random latin words.
|
||||
|
||||
now
|
||||
~~~
|
||||
|
||||
|
|
|
@ -0,0 +1,52 @@
|
|||
========================
|
||||
django.contrib.webdesign
|
||||
========================
|
||||
|
||||
The ``django.contrib.webdesign`` package, part of the `"django.contrib" add-ons`_,
|
||||
provides various Django helpers that are particularly useful to Web *designers*
|
||||
(as opposed to developers).
|
||||
|
||||
At present, the package contains only a single template tag. If you have ideas
|
||||
for Web-designer-friendly functionality in Django, please `suggest them`_.
|
||||
|
||||
.. _"django.contrib" add-ons: ../add_ons/
|
||||
.. _suggest them: ../contributing/
|
||||
|
||||
Template tags
|
||||
=============
|
||||
|
||||
To use these template tags, add ``'django.contrib.webdesign'`` to your
|
||||
``INSTALLED_APPS`` setting. Once you've done that, use
|
||||
``{% load webdesign %}`` in a template to give your template access to the tags.
|
||||
|
||||
|
||||
lorem
|
||||
=====
|
||||
|
||||
Displays random "lorem ipsum" Latin text. This is useful for providing sample
|
||||
data in templates.
|
||||
|
||||
Usage::
|
||||
|
||||
{% lorem [count] [method] [random] %}
|
||||
|
||||
The ``{% lorem %}`` tag can be used with zero, one, two or three arguments.
|
||||
The arguments are:
|
||||
|
||||
=========== =============================================================
|
||||
Argument Description
|
||||
=========== =============================================================
|
||||
``count`` A number (or variable) containing the number of paragraphs or
|
||||
words to generate (default is 1).
|
||||
``method`` Either ``w`` for words, ``p`` for HTML paragraphs or ``b``
|
||||
for plain-text paragraph blocks (default is ``b``).
|
||||
``random`` The word ``random``, which if given, does not use the common
|
||||
paragraph ("Lorem ipsum dolor sit amet...") when generating
|
||||
text.
|
||||
|
||||
Examples:
|
||||
|
||||
* ``{% lorem %}`` will output the common "lorem ipsum" paragraph.
|
||||
* ``{% lorem 3 p %}`` will output the common "lorem ipsum" paragraph
|
||||
and two random paragraphs each wrapped in HTML ``<p>`` tags.
|
||||
* ``{% lorem 2 w random %}`` will output two random Latin words.
|
|
@ -149,7 +149,7 @@ class Templates(unittest.TestCase):
|
|||
|
||||
# Dictionary lookup wins out when there is a string and int version of the key.
|
||||
'list-index07': ("{{ var.1 }}", {"var": {'1': "hello", 1: "world"}}, "hello"),
|
||||
|
||||
|
||||
# Basic filter usage
|
||||
'basic-syntax21': ("{{ var|upper }}", {"var": "Django is the greatest!"}, "DJANGO IS THE GREATEST!"),
|
||||
|
||||
|
@ -654,11 +654,6 @@ class Templates(unittest.TestCase):
|
|||
'with01': ('{% with dict.key as key %}{{ key }}{% endwith %}', {'dict': {'key':50}}, '50'),
|
||||
'with02': ('{{ key }}{% with dict.key as key %}{{ key }}-{{ dict.key }}-{{ key }}{% endwith %}{{ key }}', {'dict': {'key':50}}, ('50-50-50', 'INVALID50-50-50INVALID')),
|
||||
|
||||
### LOREM TAG ######################################################
|
||||
'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.'),
|
||||
'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>'),
|
||||
'lorem03': ('{% lorem 6 w %}', {}, 'lorem ipsum dolor sit amet consectetur'),
|
||||
|
||||
### NOW TAG ########################################################
|
||||
# Simple case
|
||||
'now01' : ('{% now "j n Y"%}', {}, str(datetime.now().day) + ' ' + str(datetime.now().month) + ' ' + str(datetime.now().year)),
|
||||
|
|
Loading…
Reference in New Issue