Only allow users to add NPC or Player characters.
[matthijs/projects/xerxes.git] / tools / templatetags / gapless.py
1 import re\r
2 \r
3 from django.utils.functional import allow_lazy\r
4 from django.utils.encoding import force_unicode\r
5 from django.template import Node, Library\r
6 \r
7 register = Library()\r
8 \r
9 def strip_empty_lines(value):\r
10     """Return the given HTML with empty and all-whitespace lines removed."""\r
11     return re.sub(r'(\n[ \t]*|(?<=\n)\\\\)(?=\n)', '', force_unicode(value))\r
12 strip_empty_lines = allow_lazy(strip_empty_lines, unicode)\r
13 \r
14 class GaplessNode(Node):\r
15     def __init__(self, nodelist):\r
16         self.nodelist = nodelist\r
17 \r
18     def render(self, context):\r
19         return strip_empty_lines(self.nodelist.render(context).strip())\r
20 \r
21 def gapless(parser, token):\r
22     """\r
23     Remove empty and whitespace-only lines.  Useful for getting rid of those\r
24     empty lines caused by template lines with only template tags and possibly\r
25     whitespace.\r
26 \r
27     Example usage::\r
28 \r
29         <p>{% gapless %}\r
30           {% if yepp %}\r
31             <a href="foo/">Foo</a>\r
32           {% endif %}\r
33         {% endgapless %}</p>\r
34 \r
35     This example would return this HTML::\r
36 \r
37         <p>\r
38             <a href="foo/">Foo</a>\r
39         </p>\r
40 \r
41     """\r
42     nodelist = parser.parse(('endgapless',))\r
43     parser.delete_first_token()\r
44     return GaplessNode(nodelist)\r
45 gapless = register.tag(gapless)\r
46 \r
47 # vim: set sw=4 sts=4 expandtab:\r