]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Add `{% whitespace %}` template directive.
authorBen Darnell <ben@bendarnell.com>
Sun, 5 Jul 2015 22:40:14 +0000 (18:40 -0400)
committerBen Darnell <ben@bendarnell.com>
Sun, 5 Jul 2015 22:40:14 +0000 (18:40 -0400)
This allows per-template and even per-section changes to whitespace
handling.

Closes #178.

tornado/template.py
tornado/test/template_test.py

index 9a4c6c64a0fa2816597b55ea5b3167fbee33f9ae..959b191d624a9132404a715f8d9c4bf9f6c0fca4 100644 (file)
@@ -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":
index 833276aed0553f0d76ce87cff7492058780b4cc6..77f42e2f0afe33d57f0e6242afe38eca82f2fb63 100644 (file)
@@ -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):