From: Ben Darnell Date: Sun, 5 Jul 2015 22:40:14 +0000 (-0400) Subject: Add `{% whitespace %}` template directive. X-Git-Tag: v4.3.0b1~76 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=d8d5f588dd034ea262fdd8e6098e3ae20c805837;p=thirdparty%2Ftornado.git Add `{% whitespace %}` template directive. This allows per-template and even per-section changes to whitespace handling. Closes #178. --- diff --git a/tornado/template.py b/tornado/template.py index 9a4c6c64a..959b191d6 100644 --- a/tornado/template.py +++ b/tornado/template.py @@ -186,6 +186,11 @@ with ``{# ... #}``. ``{% while *condition* %}... {% end %}`` Same as the python ``while`` statement. ``{% break %}`` and ``{% continue %}`` may be used inside the loop. + +``{% whitespace *mode* %}`` + Sets the whitespace mode for the remainder of the current file + (or until the next ``{% whitespace %}`` directive). See + `filter_whitespace` for available options. New in Tornado 4.3. """ from __future__ import absolute_import, division, print_function, with_statement @@ -894,7 +899,8 @@ def _parse(reader, template, in_block=None, in_loop=None): return body elif operator in ("extends", "include", "set", "import", "from", - "comment", "autoescape", "raw", "module"): + "comment", "autoescape", "whitespace", "raw", + "module"): if operator == "comment": continue if operator == "extends": @@ -921,6 +927,12 @@ def _parse(reader, template, in_block=None, in_loop=None): fn = None template.autoescape = fn continue + elif operator == "whitespace": + mode = suffix.strip() + # Validate the selected mode + filter_whitespace(mode, '') + reader.whitespace = mode + continue elif operator == "raw": block = _Expression(suffix, line, raw=True) elif operator == "module": diff --git a/tornado/test/template_test.py b/tornado/test/template_test.py index 833276aed..77f42e2f0 100644 --- a/tornado/test/template_test.py +++ b/tornado/test/template_test.py @@ -457,6 +457,19 @@ raw: {% raw name %}""", self.assertEqual(loader.load("foo.html").generate(), b" foo ") self.assertEqual(loader.load("bar.txt").generate(), b" bar ") + def test_whitespace_directive(self): + loader = DictLoader({ + "foo.html": """\ +{% whitespace oneline %} + {% for i in range(3) %} + {{ i }} + {% end %} +{% whitespace all %} + pre\tformatted +"""}) + self.assertEqual(loader.load("foo.html").generate(), + b" 0 1 2 \n pre\tformatted\n") + class TemplateLoaderTest(unittest.TestCase): def setUp(self):