Added `TemplateStream.dump`.
authorArmin Ronacher <armin.ronacher@active-4.com>
Tue, 17 Jun 2008 09:28:59 +0000 (11:28 +0200)
committerArmin Ronacher <armin.ronacher@active-4.com>
Tue, 17 Jun 2008 09:28:59 +0000 (11:28 +0200)
--HG--
branch : trunk

CHANGES
docs/api.rst
jinja2/environment.py

diff --git a/CHANGES b/CHANGES
index 4277283685b11e198ba19e86fa7c69d93e0df8b1..9d343818cf42dc28a37c1ed7095af60f6a16dbc0 100644 (file)
--- a/CHANGES
+++ b/CHANGES
@@ -17,6 +17,8 @@ Version 2.0
   This would allow extensions to allow simplified gettext calls in template
   data and something similar.
 
+- added :meth:`jinja2.environment.TemplateStream.dump`.
+
 Version 2.0rc1
 --------------
 (no codename, released on July 9th 2008)
index e16107aa64e4259132975834f44c37b10725076d..d7ed8449bbd3830b6f9cd53409041521cc832209 100644 (file)
@@ -216,7 +216,7 @@ useful if you want to dig deeper into Jinja2 or :ref:`develop extensions
 
 
 .. autoclass:: jinja2.environment.TemplateStream()
-    :members: disable_buffering, enable_buffering
+    :members: disable_buffering, enable_buffering, dump
 
 
 .. _identifier-naming:
index 94d0679e50549a4d150b42545b0007ded5de2d61..57b49ae11703bd75d44324706ddcdbe8185591ba 100644 (file)
@@ -681,6 +681,33 @@ class TemplateStream(object):
         self._gen = gen
         self.disable_buffering()
 
+    def dump(self, fp, encoding=None, errors='strict'):
+        """Dump the complete stream into a file or file-like object.
+        Per default unicode strings are written, if you want to encode
+        before writing specifiy an `encoding`.
+
+        Example usage::
+
+            Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
+        """
+        close = False
+        if isinstance(fp, basestring):
+            fp = file(fp, 'w')
+            close = True
+        try:
+            if encoding is not None:
+                iterable = (x.encode(encoding, errors) for x in self)
+            else:
+                iterable = self
+            if hasattr(fp, 'writelines'):
+                fp.writelines(iterable)
+            else:
+                for item in iterable:
+                    fp.write(item)
+        finally:
+            if close:
+                fp.close()
+
     def disable_buffering(self):
         """Disable the output buffering."""
         self._next = self._gen.next