summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMalthe Borch <mborch@gmail.com>2011-07-20 15:17:19 +0000
committerMalthe Borch <mborch@gmail.com>2011-07-20 15:17:19 +0000
commitab62edb7ee6afd361351fd8dc8ccfebb0583a142 (patch)
tree4a8753540675d58acce366a8e8d018a17bce58fc
parenta077116d36992bb867adee165819f82d993bea3e (diff)
downloadzope-pagetemplate-engine-as-component.tar.gz
This branch is a refactor of the cook- and render implementation which adds a formal interface to the parser and interpreter. In addition, a utility lookup is made for the interface such that an alternative implementation may be configured.engine-as-component
-rw-r--r--CHANGES.txt6
-rw-r--r--src/zope/pagetemplate/interfaces.py15
-rw-r--r--src/zope/pagetemplate/pagetemplate.py75
-rw-r--r--src/zope/pagetemplate/tests/test_basictemplate.py43
4 files changed, 119 insertions, 20 deletions
diff --git a/CHANGES.txt b/CHANGES.txt
index 2848efa..43395f5 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -2,6 +2,12 @@
CHANGES
=======
+3.6.0 (unreleased)
+
+- Refactor of the cook- and render implementation such that an
+ alternative implementation may be configured via utility component
+ registration.
+
3.5.3 (unreleased)
------------------
diff --git a/src/zope/pagetemplate/interfaces.py b/src/zope/pagetemplate/interfaces.py
index c627fad..c036ff3 100644
--- a/src/zope/pagetemplate/interfaces.py
+++ b/src/zope/pagetemplate/interfaces.py
@@ -98,8 +98,21 @@ class IPageTemplateSubclassing(IPageTemplate):
Subclasses might override this to influence the decision about
whether compilation is necessary.
"""
-
+
content_type = Attribute("The content-type of the generated output")
expand = Attribute(
"Flag indicating whether the read method should expand macros")
+
+
+class IPageTemplateEngine(Interface):
+ def cook(source_file, text, engine, content_type):
+ """Parse text and return template program."""
+
+
+class IPageTemplateProgram(Interface):
+ macros = Attribute(
+ "Template macros.")
+
+ def __call__(context, tal=1, showtal=-1, sourceAnnotations=0):
+ """Render template in the provided context."""
diff --git a/src/zope/pagetemplate/pagetemplate.py b/src/zope/pagetemplate/pagetemplate.py
index f9ed040..2abd728 100644
--- a/src/zope/pagetemplate/pagetemplate.py
+++ b/src/zope/pagetemplate/pagetemplate.py
@@ -21,16 +21,20 @@ from zope.tal.htmltalparser import HTMLTALParser
from zope.tal.talgenerator import TALGenerator
from zope.tal.talinterpreter import TALInterpreter
from zope.tales.engine import Engine
+from zope.component import queryUtility
# Don't use cStringIO here! It's not unicode aware.
from StringIO import StringIO
from zope.pagetemplate.interfaces import IPageTemplateSubclassing
+from zope.pagetemplate.interfaces import IPageTemplateEngine
+from zope.pagetemplate.interfaces import IPageTemplateProgram
from zope.interface import implements
-
+from zope.interface import classProvides
_default_options = {}
_error_start = '<!-- Page Template Diagnostics'
+
class PageTemplate(object):
"""Page Templates using TAL, TALES, and METAL.
@@ -61,14 +65,13 @@ class PageTemplate(object):
content_type = 'text/html'
expand = 1
_v_errors = ()
- _v_program = None
- _v_macros = None
_v_cooked = 0
+ _v_program = None
_text = ''
def macros(self):
self._cook_check()
- return self._v_macros
+ return self._v_program.macros
macros = property(macros)
@@ -106,12 +109,12 @@ class PageTemplate(object):
if self._v_errors:
raise PTRuntimeError(str(self._v_errors))
- output = StringIO(u'')
context = self.pt_getEngineContext(namespace)
- TALInterpreter(self._v_program, self._v_macros,
- context, output, tal=not source, showtal=showtal,
- strictinsert=0, sourceAnnotations=sourceAnnotations)()
- return output.getvalue()
+
+ return self._v_program(
+ context, tal=not source, showtal=showtal,
+ sourceAnnotations=sourceAnnotations
+ )
def pt_errors(self, namespace):
self._cook_check()
@@ -175,23 +178,23 @@ class PageTemplate(object):
Cooking must not fail due to compilation errors in templates.
"""
- engine = self.pt_getEngine()
+
+ pt_engine = self.pt_getEngine()
source_file = self.pt_source_file()
- if self.content_type == 'text/html':
- gen = TALGenerator(engine, xml=0, source_file=source_file)
- parser = HTMLTALParser(gen)
- else:
- gen = TALGenerator(engine, source_file=source_file)
- parser = TALParser(gen)
self._v_errors = ()
+
try:
- parser.parseString(self._text)
- self._v_program, self._v_macros = parser.getCode()
+ engine = queryUtility(
+ IPageTemplateEngine, default=PageTemplateEngine
+ )
+ self._v_program = engine.cook(
+ source_file, self._text, pt_engine, self.content_type)
except:
etype, e = sys.exc_info()[:2]
self._v_errors = ["Compilation failed",
"%s.%s: %s" % (etype.__module__, etype.__name__, e)]
+
self._v_cooked = 1
@@ -200,6 +203,42 @@ class PTRuntimeError(RuntimeError):
pass
+class PageTemplateEngine(object):
+ """Page template engine that uses the TAL interpreter to render."""
+
+ implements(IPageTemplateProgram)
+ classProvides(IPageTemplateEngine)
+
+ def __init__(self, program, macros):
+ self.macros = macros
+
+ # Internal
+ self._program = program
+
+ def __call__(self, context, **options):
+ output = StringIO(u'')
+ interpreter = TALInterpreter(
+ self._program, self.macros, context,
+ stream=output, strictinsert=0, **options
+ )
+ interpreter()
+ return output.getvalue()
+
+ @classmethod
+ def cook(cls, source_file, text, engine, content_type):
+ if content_type == 'text/html':
+ gen = TALGenerator(engine, xml=0, source_file=source_file)
+ parser = HTMLTALParser(gen)
+ else:
+ gen = TALGenerator(engine, source_file=source_file)
+ parser = TALParser(gen)
+
+ parser.parseString(text)
+ program, macros = parser.getCode()
+
+ return cls(program, macros)
+
+
class PageTemplateTracebackSupplement(object):
#implements(ITracebackSupplement)
diff --git a/src/zope/pagetemplate/tests/test_basictemplate.py b/src/zope/pagetemplate/tests/test_basictemplate.py
index d77f665..87a697f 100644
--- a/src/zope/pagetemplate/tests/test_basictemplate.py
+++ b/src/zope/pagetemplate/tests/test_basictemplate.py
@@ -17,13 +17,17 @@ import unittest
from zope.pagetemplate.tests import util
import zope.pagetemplate.pagetemplate
-
+import zope.component.testing
class BasicTemplateTests(unittest.TestCase):
def setUp(self):
+ zope.component.testing.setUp(self)
self.t = zope.pagetemplate.pagetemplate.PageTemplate()
+ def tearDown(self):
+ zope.component.testing.tearDown(self)
+
def test_if_in_var(self):
# DTML test 1: if, in, and var:
pass # for unittest
@@ -73,6 +77,43 @@ class BasicTemplateTests(unittest.TestCase):
else:
self.fail("expected PTRuntimeError")
+ def test_engine_utility_registration(self):
+ self.t.write("foo")
+ output = self.t.pt_render({})
+ self.assertEqual(output, 'foo')
+
+ from zope.pagetemplate.interfaces import IPageTemplateEngine
+ from zope.component import provideUtility
+
+ class DummyProgram(object):
+ def __init__(*args):
+ self.args = args
+
+ def __call__(*args, **kwargs):
+ return self.args, args, kwargs
+
+ class DummyEngine(object):
+ cook = DummyProgram
+
+ provideUtility(DummyEngine, IPageTemplateEngine)
+ self.t._cook()
+
+ # "Render" and unpack arguments passed for verification
+ ((cls, source_file, text, engine, content_type),
+ (program, context),
+ options) = \
+ self.t.pt_render({})
+
+ self.assertEqual(source_file, None)
+ self.assertEqual(text, 'foo')
+ self.assertEqual(content_type, 'text/html')
+ self.assertTrue(isinstance(program, DummyProgram))
+ self.assertEqual(options, {
+ 'tal': True,
+ 'showtal': False,
+ 'sourceAnnotations': False
+ })
+
def test_batches_and_formatting(self):
# DTML test 3: batches and formatting:
pass # for unittest