z3c.pt-2.2.3/0000755000175000001440000000000011762105444013274 5ustar mborchusers00000000000000z3c.pt-2.2.3/LICENSE.txt0000644000175000001440000000402611436764405015127 0ustar mborchusers00000000000000Zope Public License (ZPL) Version 2.1 A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. z3c.pt-2.2.3/buildout.cfg0000644000175000001440000000033011745501664015605 0ustar mborchusers00000000000000[buildout] develop = . parts = test py [test] recipe = zc.recipe.testrunner eggs = z3c.pt [test] [py] recipe = zc.recipe.egg eggs = z3c.pt Sphinx zope.testing interpreter = py scripts = sphinx-build z3c.pt-2.2.3/setup.cfg0000644000175000001440000000007311762105444015115 0ustar mborchusers00000000000000[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 z3c.pt-2.2.3/CHANGES.txt0000644000175000001440000006677311762105323015124 0ustar mborchusers00000000000000Changelog ========= 2.2.3 (2012-06-01) ~~~~~~~~~~~~~~~~~~ Compatibility: - The translation function now accepts (but ignores) a ``context`` argument. This fixes a compatibility issue with Chameleon 2.9.x. 2.2.2 (2012-04-24) ~~~~~~~~~~~~~~~~~~ Bugfixes: - Do not rely on the "LANGUAGE" request key to skip language negotiation. Instead, we assume that negotiation is cheap (and probably cached). 2.2.1 (2012-02-15) ~~~~~~~~~~~~~~~~~~ - Only require Chameleon >= 2.4, was needlessly bumped in last release. - Add test extra, remove versions from buildout.cfg. 2.2 (2012-01-08) ~~~~~~~~~~~~~~~~ Features: - Whitespace between attributes is now reduced to a single whitespace character. - The ``request`` symbol is no longer required to evaluate a path expression; it now defaults to ``None`` if not present in the namespace. Bugfixes: - The content provider expression now correctly applies TAL namespace data. Changes: - The ``ZopeTraverser`` class has been removed and replaced with a simple function. 2.1.5 (2011-11-24) ~~~~~~~~~~~~~~~~~~ - Use non-strict mode if available for compatibility with the reference engine where expressions are only compiled at evaluation time. 2.1.4 (2011-09-14) ~~~~~~~~~~~~~~~~~~ - The provider expression is now first evaluated as a string expression, the result of which is used as the content provider name. This fixes an issue where (provider-) string expressions would not get evaluated correctly, e.g. ``provider: ${mgr}``. 2.1.3 (2011-08-22) ~~~~~~~~~~~~~~~~~~ - Configure HTML boolean attributes (in HTML-mode only):: "compact", "nowrap", "ismap", "declare", "noshade", "checked", "disabled", "readonly", "multiple", "selected", "noresize", "defer" 2.1.2 (2011-08-19) ~~~~~~~~~~~~~~~~~~ - Enable option ``literal_false`` to get the behavior that a value of ``False`` does not drop an attribute. 2.1.1 (2011-08-11) ~~~~~~~~~~~~~~~~~~ - Make sure the builtin names 'path' and 'exists' can be redefined. - Guard ``sys.modules`` (mapped to the builtin variable "modules") against import-time side effects using ``ProxyFactory``. 2.1 (2011-07-28) ~~~~~~~~~~~~~~~~ - Use dynamic expression evaluation framework that comes included with Chameleon. 2.0 (2011-07-14) ~~~~~~~~~~~~~~~~ - Point release. - Move implementation-specific context setup to ``render`` method. This allows use of template class with an already prepared context. - Fixed issue with the call flag on the Zope traverser compiler. 2.0-rc3 (2011-07-11) ~~~~~~~~~~~~~~~~~~~~ - Python-expressions are no longer TALES-expressions; previously, the pipe operator would split Python expression clauses, allowing fallbacks even for Python expressions, but this is not the standard behavior of ZPT. - Fixed an issue where an error which occurred inside a dynamic ``path`` or ``exists`` evaluation would fail to propagate due to a missing remote context. - Set variables ``here`` and ``context`` to the bound instance value on ``PageTemplate`` instances. 2.0-rc2 (2011-03-24) ~~~~~~~~~~~~~~~~~~~~ - Fixed an issue with ``"exists:"`` expression where a callable would be attempted called. It is meanwhile implied with this expression types that it should use the ``"nocall:"`` pragma. 2.0-rc1 (2011-02-28) ~~~~~~~~~~~~~~~~~~~~ - Update to Chameleon 2.0. This release includes many changes and is a complete rewrite of the 1.x series. Platform: * Python 2.5+ now required. Notable changes: * Expression interpolation is always enabled. * Whitespace output is different, now closely aligned to the template input. * New language constructs: 1) tal:on-error 2) tal:switch 3) tal:case Incompatibilities: * The expression translation interface has been replaced with an expression engine. This means that all expressions must be rewritten. - The exists expression evaluator should ignore KeyError exceptions as well. - Special-case handling of Zope2's Missing.MV as used by Products.ZCatalog for LP#649343. [rossp] 1.2.1 (2010/05/13) ------------------ - Bind template to the template object in the general case. 1.2 (2010/05/12) ------------------ - Fixed compatibility issue with recent change in Chameleon. - Fixed regression introduced with ``args`` being passed in. Incidentally, the name ``args`` was used as the star argument name. - Look at language set on request before invoking the zope.i18n negotiator. This makes i18n work again on Zope2. 1.1.1 (2010/04/06) ------------------ - Fixed issue where arguments were not passed on to template as ``args``. 1.1.0 (2010/01/09) ------------------ - Update to combined Chameleon distribution. 1.0.1 (2009/07/06) ------------------ - Bind translation context (request) to translation method. Although not required in newer versions of the translation machinery, some versions will ask for a translation context in order to negotiate language even when a language is explicitly passed in. - Declare zope security settings for classes when zope.security is present as the "class" ZCML directive was moved there. 1.0.0 (2009/07/06) ------------------ - First point release. 1.0b17 (2009/06/14) ------------------- - Made the Zope security declaration for the repeat dictionary be conditional on the presence of zope.app.security instead of zope.app.component. 1.0b16 (2009/05/20) ------------------- - Updated run-time expression evaluator method to work after a recent architectural change in Chameleon. [malthe] - Check that we have a non-trivial response-object before trying to set the content type. [malthe] - Wrap ``sys.modules`` dictionary in an "opaque" dictionary class, such that the representation string does not list all loaded modules. [malthe] 1.0b15 (2009/04/24) ------------------- - Removed lxml extra, as we do no longer depend on it. [malthe] - Make sure the path expression is a simple string, not unicode. [malthe] - Detect path prefix properly for ViewPageTemplateFile usage in doctests. [sidnei] - The ``template`` symbol is already set by the template base class. [malthe] - Set Content-Type header, for backwards compatibility with zope.app.pagetemplate. [sidnei] 1.0b14 (2009/03/31) ------------------- - Updated language adapter to work with 'structure' meta attribute. [malthe] 1.0b13 (2009/03/23) ------------------- - When traversing on dictionaries, only exposes dictionary items (never attributes); this is to avoid ambiguity. [sidnei, malthe] - Path expressions need to pass further path items in reverse order to traversePathElement, because that's what it expects. [sidnei] 1.0b12 (2009/03/09) ------------------- - Insert initial variable context into dynamic scope. The presence of these is expected by many application. [malthe] 1.0b11 (2009/03/05) ------------------- - If a namespace-acquired object provides ``ITraversable``, use path traversal. [malthe] - Implemented TALES function namespaces. [sidnei, malthe] - Catch ``NameError`` in exists-traverser (return false). [malthe] - Catch ``NameError`` in exists-evaluator (return false). [malthe] - If the supplied ``context`` and ``request`` parameters are trivial, get them from the view instance. [malthe] - Expressions in text templates are never escaped. [malthe] - Do not bind template to a trivial instance. [malthe] 1.0b10 (2009/02/24) ------------------- - Fixed exists-traverser such that it always returns a boolean value. [malthe] 1.0b9 (2009/02/19) ------------------ - When evaluating path-expressions at runtime (e.g. the ``path`` method), run the source through the transform first to support dynamic scope. [malthe] 1.0b8 (2009/02/17) ------------------ - Allow attribute access to ``__call__`` method on bound page templates. [malthe] 1.0b7 (2009/02/13) ------------------ - Fixed issue where symbol mapping would not be carried through under a negation (not). [malthe] - Optimize simple case: if path expression is a single path and path is 'nothing' or has 'nocall:', just return value as-is, without going through path_traverse. [sidnei] - Moved evaluate_path and evaluate_exists over from ``five.pt``, adds support for global ``path()`` and ``exists()`` functions for use in ``python:`` expressions (LP #317967). - Added Zope security declaration for the repeat dictionary (tales iterator). [malthe] 1.0b6 (2008/12/18) ------------------ - The 'not' pragma acts recursively. [malthe] 1.0b5 (2008/12/15) ------------------ - View templates now support argument-passing for alternative context and request (for compatibility with ``zope.app.pagetemplate``). [malthe] - Switched off the $-interpolation feature per default; It may be activated on a per-template basis using ``meta:interpolation='true'``. [seletz] - Allow more flexibility in overriding the PathTranslator method. [hannosch] - Removed the forced defaultencoding from the benchmark suite. [hannosch] 1.0b4 (2008/11/19) ------------------ - Split out content provider function call to allow modification through subclassing. [malthe] - Added language negotiation. [malthe] - Simplified template class inheritance. [malthe] - Added support for the question-mark operator in path-expressions. [malthe] - Updated expressions to recent API changes. [malthe] - Added 'exists' and 'not' translators. [malthe] Bug fixes - Adjusted the bigtable benchmark test to API changes. [hannosch] 1.0b3 (2008/11/12) ------------------ - Added ``PageTemplate`` and ``PageTemplateFile`` classes. [malthe] 1.0b2 (2008/11/03) ------------------ Bug fixes - Allow '.' character in content provider expressions. - Allow '+' character in path-expressions. 1.0b1 (2008/10/02) ------------------ Package changes - Split out compiler to "Chameleon" package. [malthe] Backwards incompatibilities - Moved contents of ``z3c.pt.macro`` module into ``z3c.pt.template``. [malthe] - Namespace attribute "xmlns" no longer rendered for templates with no explicit document type. [malthe] - Changes to template method signatures. [malthe] - Engine now expects all strings to be unicode or contain ASCII characters only, unless an encoding is provided. [malthe] - The default path traverser no longer proxies objects. [malthe] - Template output is now always converted to unicode. [malthe] - The ``ViewPageTemplateFile`` class now uses 'path' as the default expression type. [malthe] - The compiler now expects an instantiated parser instance. [malthe] Features - Added expression translator "provider:" (which renders a content provider as defined in the ``zope.contentprovider`` package). [malthe] - Added template API to render macros. [malthe] - Optimized template loader so only a single template is instantiated per file. [malthe] - Made ``z3c.pt`` a namespace package. [malthe] - Added reduce and restore operation to the compilation and rendering flow in the test examples to verify integrity. [malthe] - The ZPT parser now supports prefixed native attributes, e.g. . [malthe] - Source-code is now written to disk in debug mode. [malthe] - Custom validation error is now raised if inserted string does not validate (when debug mode is enabled). [malthe] - Added support for omitting rendering of HTML "toggle" attributes (option's ``selected`` and input's ``checked``) within dynamic attribute assignment. If the value of the expression in the assignment evaluates equal to boolean False, the attribute will not be rendered. If the value of the expression in the assignment evaluates equal to boolean True, the attribute will be rendered and the value of the attribute will be the value returned by the expression. [chrism] - XML namespace attribute is now always printed for root tag. [malthe] - Allow standard HTML entities. [malthe] - Added compiler option to specify an implicit doctype; this is currently used by the template classes to let the loose XHTML doctype be the default. [malthe] - Added support for translation of tag body. [malthe] - Added security configuration for the TALES iterator (repeat dictionary). This is made conditional on the availability of the application security framework. [malthe] - Dynamic attributes are now ordered as they appear in the template. [malthe] - Added ``symbol_mapping`` attribute to code streams such that function dependencies can be registered at compile-time. [malthe] - Allow BaseTemplate-derived classes (PageTemplate, PageTemplateFile, et. al) to accept a ``doctype`` argument, which will override the doctype supplied by the source of the template if specified. [chrism] - Language negotiation is left to the page template superclass, so we don't need to pass in a translation context anymore. [malthe] - The ``ViewPageTemplateFile`` class now uses the module path of the calling class to get an absolute path to a relative filename passed to the constructor. [malthe] - Added limited support for the XInclude ``include`` directive. The implemented subset corresponds to the Genshi implementation, except Match-templates, which are not made available to the calling template. [malthe] - Use a global template registry for templates on the file-system. This makes it inexpensive to have multiple template class instances pointing to the same file. [malthe] - Reimplemented the disk cache to correctly restore all template data. This implementation keeps a cache in a pickled format in a file next to the original template. [malthe] - Refactored compilation classes to better separate concerns. [malthe] - Genshi macros (py:def) are now available globally. [malthe] - A syntax error is now raised when an interpolation expression is not exhausted, e.g. only a part of the string is a valid Python-expression. [malthe] - System variables are now defined in a configuration class. [malthe] - Improve performance of codegen by not repeatedly calling an expensive "flatten" function. [chrism] - Remove ``safe_render`` implementation detail. It hid information in tracebacks. [chrism] - Implemented TAL global defines. [malthe] - Added support for variables with global scope. [malthe] - Curly braces may now be omitted in an expression interpolation if the expression is just a variable name; this complies with the Genshi syntax. [malthe] - UTF-8 encode Unicode attribute literals. [chrism] - Substantially reduced compiler overhead for lxml CDATA workaround. [malthe] - Split out element compiler classes for Genshi and Zope language dialects. [malthe] - Make lxml a setuptools "extra". To install with lxml support (currently required by Genshi), specify "z3c.pt [lxml]" in any references you need to make to the package in buildout or in setup.py install_requires. [chrism] - Add test-nolxml and py-nolxml parts to buildout so the package's tests can be run without lxml. [chrism] - No longer require default namespace. [malthe] - Changed source code debug mode files to be named .py instead of .source. - Generalized ElementTree-import to allow both Python 2.5's ``xml.etree`` module and the standalone ``ElementTree`` package. [malthe] - Expression results are now validated for XML correctness when the compiler is running in debug-mode. [malthe] - Preliminary support for using ``xml.etree`` as fallback for ``lxml.etree``. [malthe] - String-expressions may now contain semi-colons using a double semi-colon literal (;;). [malthe] - Preserve CDATA sections. [malthe] - Get rid of package-relative magic in constructor of BaseTemplateFile in favor of just requiring an absolute path or a path relative to getcwd(). Rationale: it didn't work when called from __main__ when the template was relative to getcwd(), which is the 99% case for people first trying it out. [chrism] - Added support for METAL. [malthe] - Add a TemplateLoader class to have a convenient method to instantiate templates. This is similar to the template loaders from other template toolkits and makes integration with Pylons a lot simpler. [wichert] - Switch from hardcoding all options in config.py to using parameters for the template. This also allows us to use the more logical auto_reload flag instead of reusing PROD_MODE, which is also used for other purposes. [wichert] - Treat comments, processing instructions, and named entities in the source template as "literals", which will be rendered into the output unchanged. [chrism] Bugfixes - Skip elements in a "define-slot" clause if its being filled by the calling template. [malthe] - Support "fill-slot" on elements with METAL namespace. [malthe] - Omit element text when rendering macro. [malthe] - ``Macros`` class should not return callable functions, but rather a ``Macro`` object, which has a ``render``-method. This makes it possible to use a path-expression to get to a macro without calling it. [malthe] - Fixed bug where a repeat-clause would reset the repeat variable before evaluating the expression. [malthe] - Fixed an issue related to correct restoring of ghosted template objects. [malthe] - Implicit doctype is correctly reestablished from cache. [malthe] - Remove namespace declaration on root tag to work around syntax error raised when parsing an XML tree loaded from the file cache. [malthe] - Attribute assignments with an expression value that started with the characters ``in`` (e.g. ``info.somename``) would be rendered to the generated Python without the ``in`` prefix (as e.g. ``fo.somename``). [chrism] - When filling METAL slots (possibly with a specific version of libxml2, I am using 2.6.32) it was possible to cause the translator to attempt to add a stringtype to a NoneType (on a line that reads ``variable = self.symbols.slot+element.node.fill_slot`` because an XPath expression looking for fill-slot nodes did not work properly). [chrism] - Preserve whitespace in string translation expressions. [malthe] - Fixed interpolation bug where multiple attributes with interpolation expressions would result in corrupted output. [malthe] - Support try-except operator ('|') when 'python' is the default expression type. [malthe] - METAL macros should render in the template where they're defined. [malthe] - Avoid printing a line-break when we repeat over a single item only. [malthe] - Corrected Genshi namespace (needs a trailing slash). [malthe] - Fixed a few more UnicodeDecodeErrors (test contributed by Wiggy). In particular, never upcast to unicode during transformation, and utf-8 encode Unicode attribute keys and values in Assign expressions (e.g. py:attrs). [chrism] - Fixed off-by-one bug in interpolation routine. [malthe] - The repeat-clause should not output tail with every iteration. [malthe] - CDATA sections are now correctly handled when using the ElementTree-parser. [malthe] - Fixed bug in path-expressions where string instances would be (attempted) called. [malthe] - CDATA sections are now correctly preserved when using expression interpolation. [malthe] - The Genshi interpolation operator ${} should not have its result escaped when used in the text or tail regions. [malthe] - Fixed edge case bug where inserting both a numeric entity and a literal set of unicode bytes into the same document would cause a UnicodeDecodeError. See also http://groups.google.com/group/z3c_pt/browse_thread/thread/aea963d25a1778d0?hl=en [chrism] - Static attributes are now properly overriden by py:attr-attributes. [malthe] 0.9 (2008/08/07) ---------------- - Added support for Genshi-templates. [malthe] - Cleanup and refactoring of translation module. [malthe] - If the template source contains a DOCTYPE declaration, output it during rendering. [chrism] - Fixed an error where numeric entities specified in text or tail portions of elements would cause a UnicodeDecodeError to be raised on systems configured with an 'ascii' default encoding. [chrism] - Refactored file system based cache a bit and added a simple benchmark for the cache. The initial load speed for a template goes down significantly with the cache. Compared to zope.pagetemplate we are only 3x slower, compared to 50x slower when cooking each template on process startup. - Got rid entirely of the _escape function and inlined the actual code instead. We go up again to 12x for path and 19x for Python expressions :) [hannosch] - Avoid string concatenation and use multiple write statements instead. These are faster now, since we use a list append internally. [hannosch] - Inline the _escape function, because function calls are expensive in Python. Added missing escaping for Unicode values. [fschulze, hannosch] - When templates are instantiated outside of a class-definition, a relative file path will be made absolute using the module path. [malthe] - Simplified the _escape function handling by pulling in the str call into the function. Corrected the bigtable hotshot test to only benchmark rendering. - Replaced the cgi.escape function by an optimized local version, we go up to 11x for path and 16x for Python expressions :) In the bigtable benchmark the enhancement is more noticable - we are the same speed as spitfire -O1 templates now and just half the speed of -O3 :)) - Added a new benchmark test called bigtable that produces results which are directly comparable to those produced by the bigtable.py benchmark in the spitfire project. - Introduce a new config option called `Z3C_PT_DISABLE_I18N`. If this environment variable is set to `true`, the template engine will not call into the zope.i18n machinery anymore, but fall back to simple interpolation in all cases. In a normal Zope environment that has the whole i18n infrastructure set up, this will render the templates about 15x faster than normal TAL, instead of only 10x faster at this point. - Removed the `second rendering` tests from the benchmark suite. Since we enable the file cache for the benchmarks, there's no difference between the first and second rendering anymore after the cache file has been written. - Require zope.i18n 3.5 and add support for using its new negotiate function. If you use the `zope_i18n_allowed_languages` environment variable the target language for a template is only negotiated once per template, instead of once for each translate function call. This more than doubles the speed and the benchmark is back at 9.2 times faster. - Extended the i18n handling to respect the passed in translation context to the template. Usually this is the request, which is passed on under the internal name of `_context` into the render functions. After extending the i18n tests to include a negotiator and message catalog the improvement is only at 4.5 anymore, as most of the time is spent inside the i18n machinery. - Added persistent file cache functionality. If the environment variable is set, each file system based template will add a directory to the cache (currently a SHA-1 of the file's absolute path is used as the folder name) and in the folder one file per params for the template (cache filename is the hash of the params). Once a template file is initialized, an instance local registry is added, which then looks up all cached files and pre-populates the registry with the render functions. - Fixed interpolation edge case bugs. [malthe] - Added new `Z3C_PT_FILECACHE` environment variable pointing to a directory. If set, this will be used to cache the compiled files. - Added a second variation of the repeat clause, using a simple for loop. It doesn't support the repeatdict, though and is therefor not used yet. Also began work to add introspection facilities to clauses about the variables being used in them. The simpler loop causes the benchmarks to go up to a 10.5 (old 9.5) for path expressions and 14.5 (12.5) for python expressions. So the next step is to introduce an optimization phase, that can decide which variant of the loops to use. - Made the debug mode independent from the Python debug mode. You can now specify an environment variable called `Z3C_PT_DEBUG` to enable it. - Added some code in a filecache module that can later be used to write out and reload the compiled Python code to and from the file system. We should be able to avoid reparsing on Python process restart. - Simplified the generated _escape code. cgi.escape's second argument is a simple boolean and not a list of characters to quote. - Use a simple list based BufferIO class instead of a cStringIO for the out stream. Avoiding the need to encode Unicode data is a bigger win. We do not support arbitrarily mixing of Unicode and non-ascii inside the engine. - Merged two adjacent writes into one inside the Tag clause. - Applied a bunch of micro-optimizations. ''.join({}) is slightly faster than ''.join({}.keys()) and does the same. Avoid a try/except for error handling in non-debug mode. Test against 'is None' instead of a boolean check for the result of the template registry lookup. Made PROD_MODE available defined as 'not DEBUG_MODE' in config.py, so we avoid the 'not' in every cook-check. - Added more benchmark tests for the file variants. - Optimized 'is None' handling in Tag clause similar to the Write clause. - Made the _out.write method directly available as _write in all scopes, so we avoid the method lookup call each time. - Optimized 'is None' handling in Write clause. - Slightly refactored benchmark tests and added tests for the file variants. - In debug mode the actual source code for file templates is written out to a .source file, to make it easier to inspect it. - Make debug mode setting explicit in a config.py. Currently it is bound to Python's __debug__, which is False when run with -O and otherwise True. - Use a simplified UnicodeWrite clause for the result of _translate calls, as the result value is guaranteed to be Unicode. - Added benchmark tests for i18n handling. - Added more tests for i18n attributes handling. - Don't generate empty mappings for expressions with a trailing semicolon. - Fixed undefined name 'static' error in i18n attributes handling and added quoting to i18n attributes. - Added condition to the valid attributes on tags in the tal namespace. - Made sure the traceback from the *first* template exception is carried over to __traceback_info__ - Added template source annotations on exceptions raised while rendering a template. 0.8 (2008/03/19) ---------------- - Added support for 'nocall' and 'not' (for path-expressions). - Added support for path- and string-expressions. - Abstracted expression translation engine. Expression implementations are now pluggable. Expression name pragmas are supported throughout. - Formalized expression types - Added support for 'structure'-keyword for replace and content. - Result of 'replace' and 'content' is now escaped by default. - Benchmark is now built as a custom testrunner 0.7 (2008/03/10) ---------------- - Added support for comments; expressions are allowed inside comments, i.e. Comments are always included. 0.7 (2008/02/24) ---------------- - Added support for text templates; these allow expression interpolation in non-XML documents like CSS stylesheets and javascript files. 0.5 (2008/02/23) ---------------- - Expression interpolation implemented. 0.4 (2008/02/22) ---------------- - Engine now uses cStringIO yielding a 2.5x performance improvement. Unicode is now handled correctly. 0.3 (2007/12/23) ---------------- - Code optimization; bug fixing spree - Added ``ViewPageTemplateFile`` class - Added support for i18n - Engine rewrite; improved code generation abstractions 0.2 (2007/12/05) ---------------- - Major optimizations to the generated code 0.1 (2007/12/03) ---------------- - First public release z3c.pt-2.2.3/CONTRIBUTORS.txt0000644000175000001440000000016011436764405015775 0ustar mborchusers00000000000000Chris McDonough Florian Schulze Hanno Schlichting Philipp von Weitershausen Wichert Akkerman Stefan Eletzhofer z3c.pt-2.2.3/PKG-INFO0000644000175000001440000010603711762105444014400 0ustar mborchusers00000000000000Metadata-Version: 1.1 Name: z3c.pt Version: 2.2.3 Summary: Fast ZPT engine. Home-page: UNKNOWN Author: Malthe Borch and the Zope Community Author-email: zope-dev@zope.org License: ZPL Description: Overview ======== This is a fast implementation of the ZPT template engine for Zope 3 which uses Chameleon to compile templates to byte-code. The package provides application support equivalent to ``zope.app.pagetemplate``. For usage, see the README.txt file inside the package. Changelog ========= 2.2.3 (2012-06-01) ~~~~~~~~~~~~~~~~~~ Compatibility: - The translation function now accepts (but ignores) a ``context`` argument. This fixes a compatibility issue with Chameleon 2.9.x. 2.2.2 (2012-04-24) ~~~~~~~~~~~~~~~~~~ Bugfixes: - Do not rely on the "LANGUAGE" request key to skip language negotiation. Instead, we assume that negotiation is cheap (and probably cached). 2.2.1 (2012-02-15) ~~~~~~~~~~~~~~~~~~ - Only require Chameleon >= 2.4, was needlessly bumped in last release. - Add test extra, remove versions from buildout.cfg. 2.2 (2012-01-08) ~~~~~~~~~~~~~~~~ Features: - Whitespace between attributes is now reduced to a single whitespace character. - The ``request`` symbol is no longer required to evaluate a path expression; it now defaults to ``None`` if not present in the namespace. Bugfixes: - The content provider expression now correctly applies TAL namespace data. Changes: - The ``ZopeTraverser`` class has been removed and replaced with a simple function. 2.1.5 (2011-11-24) ~~~~~~~~~~~~~~~~~~ - Use non-strict mode if available for compatibility with the reference engine where expressions are only compiled at evaluation time. 2.1.4 (2011-09-14) ~~~~~~~~~~~~~~~~~~ - The provider expression is now first evaluated as a string expression, the result of which is used as the content provider name. This fixes an issue where (provider-) string expressions would not get evaluated correctly, e.g. ``provider: ${mgr}``. 2.1.3 (2011-08-22) ~~~~~~~~~~~~~~~~~~ - Configure HTML boolean attributes (in HTML-mode only):: "compact", "nowrap", "ismap", "declare", "noshade", "checked", "disabled", "readonly", "multiple", "selected", "noresize", "defer" 2.1.2 (2011-08-19) ~~~~~~~~~~~~~~~~~~ - Enable option ``literal_false`` to get the behavior that a value of ``False`` does not drop an attribute. 2.1.1 (2011-08-11) ~~~~~~~~~~~~~~~~~~ - Make sure the builtin names 'path' and 'exists' can be redefined. - Guard ``sys.modules`` (mapped to the builtin variable "modules") against import-time side effects using ``ProxyFactory``. 2.1 (2011-07-28) ~~~~~~~~~~~~~~~~ - Use dynamic expression evaluation framework that comes included with Chameleon. 2.0 (2011-07-14) ~~~~~~~~~~~~~~~~ - Point release. - Move implementation-specific context setup to ``render`` method. This allows use of template class with an already prepared context. - Fixed issue with the call flag on the Zope traverser compiler. 2.0-rc3 (2011-07-11) ~~~~~~~~~~~~~~~~~~~~ - Python-expressions are no longer TALES-expressions; previously, the pipe operator would split Python expression clauses, allowing fallbacks even for Python expressions, but this is not the standard behavior of ZPT. - Fixed an issue where an error which occurred inside a dynamic ``path`` or ``exists`` evaluation would fail to propagate due to a missing remote context. - Set variables ``here`` and ``context`` to the bound instance value on ``PageTemplate`` instances. 2.0-rc2 (2011-03-24) ~~~~~~~~~~~~~~~~~~~~ - Fixed an issue with ``"exists:"`` expression where a callable would be attempted called. It is meanwhile implied with this expression types that it should use the ``"nocall:"`` pragma. 2.0-rc1 (2011-02-28) ~~~~~~~~~~~~~~~~~~~~ - Update to Chameleon 2.0. This release includes many changes and is a complete rewrite of the 1.x series. Platform: * Python 2.5+ now required. Notable changes: * Expression interpolation is always enabled. * Whitespace output is different, now closely aligned to the template input. * New language constructs: 1) tal:on-error 2) tal:switch 3) tal:case Incompatibilities: * The expression translation interface has been replaced with an expression engine. This means that all expressions must be rewritten. - The exists expression evaluator should ignore KeyError exceptions as well. - Special-case handling of Zope2's Missing.MV as used by Products.ZCatalog for LP#649343. [rossp] 1.2.1 (2010/05/13) ------------------ - Bind template to the template object in the general case. 1.2 (2010/05/12) ------------------ - Fixed compatibility issue with recent change in Chameleon. - Fixed regression introduced with ``args`` being passed in. Incidentally, the name ``args`` was used as the star argument name. - Look at language set on request before invoking the zope.i18n negotiator. This makes i18n work again on Zope2. 1.1.1 (2010/04/06) ------------------ - Fixed issue where arguments were not passed on to template as ``args``. 1.1.0 (2010/01/09) ------------------ - Update to combined Chameleon distribution. 1.0.1 (2009/07/06) ------------------ - Bind translation context (request) to translation method. Although not required in newer versions of the translation machinery, some versions will ask for a translation context in order to negotiate language even when a language is explicitly passed in. - Declare zope security settings for classes when zope.security is present as the "class" ZCML directive was moved there. 1.0.0 (2009/07/06) ------------------ - First point release. 1.0b17 (2009/06/14) ------------------- - Made the Zope security declaration for the repeat dictionary be conditional on the presence of zope.app.security instead of zope.app.component. 1.0b16 (2009/05/20) ------------------- - Updated run-time expression evaluator method to work after a recent architectural change in Chameleon. [malthe] - Check that we have a non-trivial response-object before trying to set the content type. [malthe] - Wrap ``sys.modules`` dictionary in an "opaque" dictionary class, such that the representation string does not list all loaded modules. [malthe] 1.0b15 (2009/04/24) ------------------- - Removed lxml extra, as we do no longer depend on it. [malthe] - Make sure the path expression is a simple string, not unicode. [malthe] - Detect path prefix properly for ViewPageTemplateFile usage in doctests. [sidnei] - The ``template`` symbol is already set by the template base class. [malthe] - Set Content-Type header, for backwards compatibility with zope.app.pagetemplate. [sidnei] 1.0b14 (2009/03/31) ------------------- - Updated language adapter to work with 'structure' meta attribute. [malthe] 1.0b13 (2009/03/23) ------------------- - When traversing on dictionaries, only exposes dictionary items (never attributes); this is to avoid ambiguity. [sidnei, malthe] - Path expressions need to pass further path items in reverse order to traversePathElement, because that's what it expects. [sidnei] 1.0b12 (2009/03/09) ------------------- - Insert initial variable context into dynamic scope. The presence of these is expected by many application. [malthe] 1.0b11 (2009/03/05) ------------------- - If a namespace-acquired object provides ``ITraversable``, use path traversal. [malthe] - Implemented TALES function namespaces. [sidnei, malthe] - Catch ``NameError`` in exists-traverser (return false). [malthe] - Catch ``NameError`` in exists-evaluator (return false). [malthe] - If the supplied ``context`` and ``request`` parameters are trivial, get them from the view instance. [malthe] - Expressions in text templates are never escaped. [malthe] - Do not bind template to a trivial instance. [malthe] 1.0b10 (2009/02/24) ------------------- - Fixed exists-traverser such that it always returns a boolean value. [malthe] 1.0b9 (2009/02/19) ------------------ - When evaluating path-expressions at runtime (e.g. the ``path`` method), run the source through the transform first to support dynamic scope. [malthe] 1.0b8 (2009/02/17) ------------------ - Allow attribute access to ``__call__`` method on bound page templates. [malthe] 1.0b7 (2009/02/13) ------------------ - Fixed issue where symbol mapping would not be carried through under a negation (not). [malthe] - Optimize simple case: if path expression is a single path and path is 'nothing' or has 'nocall:', just return value as-is, without going through path_traverse. [sidnei] - Moved evaluate_path and evaluate_exists over from ``five.pt``, adds support for global ``path()`` and ``exists()`` functions for use in ``python:`` expressions (LP #317967). - Added Zope security declaration for the repeat dictionary (tales iterator). [malthe] 1.0b6 (2008/12/18) ------------------ - The 'not' pragma acts recursively. [malthe] 1.0b5 (2008/12/15) ------------------ - View templates now support argument-passing for alternative context and request (for compatibility with ``zope.app.pagetemplate``). [malthe] - Switched off the $-interpolation feature per default; It may be activated on a per-template basis using ``meta:interpolation='true'``. [seletz] - Allow more flexibility in overriding the PathTranslator method. [hannosch] - Removed the forced defaultencoding from the benchmark suite. [hannosch] 1.0b4 (2008/11/19) ------------------ - Split out content provider function call to allow modification through subclassing. [malthe] - Added language negotiation. [malthe] - Simplified template class inheritance. [malthe] - Added support for the question-mark operator in path-expressions. [malthe] - Updated expressions to recent API changes. [malthe] - Added 'exists' and 'not' translators. [malthe] Bug fixes - Adjusted the bigtable benchmark test to API changes. [hannosch] 1.0b3 (2008/11/12) ------------------ - Added ``PageTemplate`` and ``PageTemplateFile`` classes. [malthe] 1.0b2 (2008/11/03) ------------------ Bug fixes - Allow '.' character in content provider expressions. - Allow '+' character in path-expressions. 1.0b1 (2008/10/02) ------------------ Package changes - Split out compiler to "Chameleon" package. [malthe] Backwards incompatibilities - Moved contents of ``z3c.pt.macro`` module into ``z3c.pt.template``. [malthe] - Namespace attribute "xmlns" no longer rendered for templates with no explicit document type. [malthe] - Changes to template method signatures. [malthe] - Engine now expects all strings to be unicode or contain ASCII characters only, unless an encoding is provided. [malthe] - The default path traverser no longer proxies objects. [malthe] - Template output is now always converted to unicode. [malthe] - The ``ViewPageTemplateFile`` class now uses 'path' as the default expression type. [malthe] - The compiler now expects an instantiated parser instance. [malthe] Features - Added expression translator "provider:" (which renders a content provider as defined in the ``zope.contentprovider`` package). [malthe] - Added template API to render macros. [malthe] - Optimized template loader so only a single template is instantiated per file. [malthe] - Made ``z3c.pt`` a namespace package. [malthe] - Added reduce and restore operation to the compilation and rendering flow in the test examples to verify integrity. [malthe] - The ZPT parser now supports prefixed native attributes, e.g. . [malthe] - Source-code is now written to disk in debug mode. [malthe] - Custom validation error is now raised if inserted string does not validate (when debug mode is enabled). [malthe] - Added support for omitting rendering of HTML "toggle" attributes (option's ``selected`` and input's ``checked``) within dynamic attribute assignment. If the value of the expression in the assignment evaluates equal to boolean False, the attribute will not be rendered. If the value of the expression in the assignment evaluates equal to boolean True, the attribute will be rendered and the value of the attribute will be the value returned by the expression. [chrism] - XML namespace attribute is now always printed for root tag. [malthe] - Allow standard HTML entities. [malthe] - Added compiler option to specify an implicit doctype; this is currently used by the template classes to let the loose XHTML doctype be the default. [malthe] - Added support for translation of tag body. [malthe] - Added security configuration for the TALES iterator (repeat dictionary). This is made conditional on the availability of the application security framework. [malthe] - Dynamic attributes are now ordered as they appear in the template. [malthe] - Added ``symbol_mapping`` attribute to code streams such that function dependencies can be registered at compile-time. [malthe] - Allow BaseTemplate-derived classes (PageTemplate, PageTemplateFile, et. al) to accept a ``doctype`` argument, which will override the doctype supplied by the source of the template if specified. [chrism] - Language negotiation is left to the page template superclass, so we don't need to pass in a translation context anymore. [malthe] - The ``ViewPageTemplateFile`` class now uses the module path of the calling class to get an absolute path to a relative filename passed to the constructor. [malthe] - Added limited support for the XInclude ``include`` directive. The implemented subset corresponds to the Genshi implementation, except Match-templates, which are not made available to the calling template. [malthe] - Use a global template registry for templates on the file-system. This makes it inexpensive to have multiple template class instances pointing to the same file. [malthe] - Reimplemented the disk cache to correctly restore all template data. This implementation keeps a cache in a pickled format in a file next to the original template. [malthe] - Refactored compilation classes to better separate concerns. [malthe] - Genshi macros (py:def) are now available globally. [malthe] - A syntax error is now raised when an interpolation expression is not exhausted, e.g. only a part of the string is a valid Python-expression. [malthe] - System variables are now defined in a configuration class. [malthe] - Improve performance of codegen by not repeatedly calling an expensive "flatten" function. [chrism] - Remove ``safe_render`` implementation detail. It hid information in tracebacks. [chrism] - Implemented TAL global defines. [malthe] - Added support for variables with global scope. [malthe] - Curly braces may now be omitted in an expression interpolation if the expression is just a variable name; this complies with the Genshi syntax. [malthe] - UTF-8 encode Unicode attribute literals. [chrism] - Substantially reduced compiler overhead for lxml CDATA workaround. [malthe] - Split out element compiler classes for Genshi and Zope language dialects. [malthe] - Make lxml a setuptools "extra". To install with lxml support (currently required by Genshi), specify "z3c.pt [lxml]" in any references you need to make to the package in buildout or in setup.py install_requires. [chrism] - Add test-nolxml and py-nolxml parts to buildout so the package's tests can be run without lxml. [chrism] - No longer require default namespace. [malthe] - Changed source code debug mode files to be named .py instead of .source. - Generalized ElementTree-import to allow both Python 2.5's ``xml.etree`` module and the standalone ``ElementTree`` package. [malthe] - Expression results are now validated for XML correctness when the compiler is running in debug-mode. [malthe] - Preliminary support for using ``xml.etree`` as fallback for ``lxml.etree``. [malthe] - String-expressions may now contain semi-colons using a double semi-colon literal (;;). [malthe] - Preserve CDATA sections. [malthe] - Get rid of package-relative magic in constructor of BaseTemplateFile in favor of just requiring an absolute path or a path relative to getcwd(). Rationale: it didn't work when called from __main__ when the template was relative to getcwd(), which is the 99% case for people first trying it out. [chrism] - Added support for METAL. [malthe] - Add a TemplateLoader class to have a convenient method to instantiate templates. This is similar to the template loaders from other template toolkits and makes integration with Pylons a lot simpler. [wichert] - Switch from hardcoding all options in config.py to using parameters for the template. This also allows us to use the more logical auto_reload flag instead of reusing PROD_MODE, which is also used for other purposes. [wichert] - Treat comments, processing instructions, and named entities in the source template as "literals", which will be rendered into the output unchanged. [chrism] Bugfixes - Skip elements in a "define-slot" clause if its being filled by the calling template. [malthe] - Support "fill-slot" on elements with METAL namespace. [malthe] - Omit element text when rendering macro. [malthe] - ``Macros`` class should not return callable functions, but rather a ``Macro`` object, which has a ``render``-method. This makes it possible to use a path-expression to get to a macro without calling it. [malthe] - Fixed bug where a repeat-clause would reset the repeat variable before evaluating the expression. [malthe] - Fixed an issue related to correct restoring of ghosted template objects. [malthe] - Implicit doctype is correctly reestablished from cache. [malthe] - Remove namespace declaration on root tag to work around syntax error raised when parsing an XML tree loaded from the file cache. [malthe] - Attribute assignments with an expression value that started with the characters ``in`` (e.g. ``info.somename``) would be rendered to the generated Python without the ``in`` prefix (as e.g. ``fo.somename``). [chrism] - When filling METAL slots (possibly with a specific version of libxml2, I am using 2.6.32) it was possible to cause the translator to attempt to add a stringtype to a NoneType (on a line that reads ``variable = self.symbols.slot+element.node.fill_slot`` because an XPath expression looking for fill-slot nodes did not work properly). [chrism] - Preserve whitespace in string translation expressions. [malthe] - Fixed interpolation bug where multiple attributes with interpolation expressions would result in corrupted output. [malthe] - Support try-except operator ('|') when 'python' is the default expression type. [malthe] - METAL macros should render in the template where they're defined. [malthe] - Avoid printing a line-break when we repeat over a single item only. [malthe] - Corrected Genshi namespace (needs a trailing slash). [malthe] - Fixed a few more UnicodeDecodeErrors (test contributed by Wiggy). In particular, never upcast to unicode during transformation, and utf-8 encode Unicode attribute keys and values in Assign expressions (e.g. py:attrs). [chrism] - Fixed off-by-one bug in interpolation routine. [malthe] - The repeat-clause should not output tail with every iteration. [malthe] - CDATA sections are now correctly handled when using the ElementTree-parser. [malthe] - Fixed bug in path-expressions where string instances would be (attempted) called. [malthe] - CDATA sections are now correctly preserved when using expression interpolation. [malthe] - The Genshi interpolation operator ${} should not have its result escaped when used in the text or tail regions. [malthe] - Fixed edge case bug where inserting both a numeric entity and a literal set of unicode bytes into the same document would cause a UnicodeDecodeError. See also http://groups.google.com/group/z3c_pt/browse_thread/thread/aea963d25a1778d0?hl=en [chrism] - Static attributes are now properly overriden by py:attr-attributes. [malthe] 0.9 (2008/08/07) ---------------- - Added support for Genshi-templates. [malthe] - Cleanup and refactoring of translation module. [malthe] - If the template source contains a DOCTYPE declaration, output it during rendering. [chrism] - Fixed an error where numeric entities specified in text or tail portions of elements would cause a UnicodeDecodeError to be raised on systems configured with an 'ascii' default encoding. [chrism] - Refactored file system based cache a bit and added a simple benchmark for the cache. The initial load speed for a template goes down significantly with the cache. Compared to zope.pagetemplate we are only 3x slower, compared to 50x slower when cooking each template on process startup. - Got rid entirely of the _escape function and inlined the actual code instead. We go up again to 12x for path and 19x for Python expressions :) [hannosch] - Avoid string concatenation and use multiple write statements instead. These are faster now, since we use a list append internally. [hannosch] - Inline the _escape function, because function calls are expensive in Python. Added missing escaping for Unicode values. [fschulze, hannosch] - When templates are instantiated outside of a class-definition, a relative file path will be made absolute using the module path. [malthe] - Simplified the _escape function handling by pulling in the str call into the function. Corrected the bigtable hotshot test to only benchmark rendering. - Replaced the cgi.escape function by an optimized local version, we go up to 11x for path and 16x for Python expressions :) In the bigtable benchmark the enhancement is more noticable - we are the same speed as spitfire -O1 templates now and just half the speed of -O3 :)) - Added a new benchmark test called bigtable that produces results which are directly comparable to those produced by the bigtable.py benchmark in the spitfire project. - Introduce a new config option called `Z3C_PT_DISABLE_I18N`. If this environment variable is set to `true`, the template engine will not call into the zope.i18n machinery anymore, but fall back to simple interpolation in all cases. In a normal Zope environment that has the whole i18n infrastructure set up, this will render the templates about 15x faster than normal TAL, instead of only 10x faster at this point. - Removed the `second rendering` tests from the benchmark suite. Since we enable the file cache for the benchmarks, there's no difference between the first and second rendering anymore after the cache file has been written. - Require zope.i18n 3.5 and add support for using its new negotiate function. If you use the `zope_i18n_allowed_languages` environment variable the target language for a template is only negotiated once per template, instead of once for each translate function call. This more than doubles the speed and the benchmark is back at 9.2 times faster. - Extended the i18n handling to respect the passed in translation context to the template. Usually this is the request, which is passed on under the internal name of `_context` into the render functions. After extending the i18n tests to include a negotiator and message catalog the improvement is only at 4.5 anymore, as most of the time is spent inside the i18n machinery. - Added persistent file cache functionality. If the environment variable is set, each file system based template will add a directory to the cache (currently a SHA-1 of the file's absolute path is used as the folder name) and in the folder one file per params for the template (cache filename is the hash of the params). Once a template file is initialized, an instance local registry is added, which then looks up all cached files and pre-populates the registry with the render functions. - Fixed interpolation edge case bugs. [malthe] - Added new `Z3C_PT_FILECACHE` environment variable pointing to a directory. If set, this will be used to cache the compiled files. - Added a second variation of the repeat clause, using a simple for loop. It doesn't support the repeatdict, though and is therefor not used yet. Also began work to add introspection facilities to clauses about the variables being used in them. The simpler loop causes the benchmarks to go up to a 10.5 (old 9.5) for path expressions and 14.5 (12.5) for python expressions. So the next step is to introduce an optimization phase, that can decide which variant of the loops to use. - Made the debug mode independent from the Python debug mode. You can now specify an environment variable called `Z3C_PT_DEBUG` to enable it. - Added some code in a filecache module that can later be used to write out and reload the compiled Python code to and from the file system. We should be able to avoid reparsing on Python process restart. - Simplified the generated _escape code. cgi.escape's second argument is a simple boolean and not a list of characters to quote. - Use a simple list based BufferIO class instead of a cStringIO for the out stream. Avoiding the need to encode Unicode data is a bigger win. We do not support arbitrarily mixing of Unicode and non-ascii inside the engine. - Merged two adjacent writes into one inside the Tag clause. - Applied a bunch of micro-optimizations. ''.join({}) is slightly faster than ''.join({}.keys()) and does the same. Avoid a try/except for error handling in non-debug mode. Test against 'is None' instead of a boolean check for the result of the template registry lookup. Made PROD_MODE available defined as 'not DEBUG_MODE' in config.py, so we avoid the 'not' in every cook-check. - Added more benchmark tests for the file variants. - Optimized 'is None' handling in Tag clause similar to the Write clause. - Made the _out.write method directly available as _write in all scopes, so we avoid the method lookup call each time. - Optimized 'is None' handling in Write clause. - Slightly refactored benchmark tests and added tests for the file variants. - In debug mode the actual source code for file templates is written out to a .source file, to make it easier to inspect it. - Make debug mode setting explicit in a config.py. Currently it is bound to Python's __debug__, which is False when run with -O and otherwise True. - Use a simplified UnicodeWrite clause for the result of _translate calls, as the result value is guaranteed to be Unicode. - Added benchmark tests for i18n handling. - Added more tests for i18n attributes handling. - Don't generate empty mappings for expressions with a trailing semicolon. - Fixed undefined name 'static' error in i18n attributes handling and added quoting to i18n attributes. - Added condition to the valid attributes on tags in the tal namespace. - Made sure the traceback from the *first* template exception is carried over to __traceback_info__ - Added template source annotations on exceptions raised while rendering a template. 0.8 (2008/03/19) ---------------- - Added support for 'nocall' and 'not' (for path-expressions). - Added support for path- and string-expressions. - Abstracted expression translation engine. Expression implementations are now pluggable. Expression name pragmas are supported throughout. - Formalized expression types - Added support for 'structure'-keyword for replace and content. - Result of 'replace' and 'content' is now escaped by default. - Benchmark is now built as a custom testrunner 0.7 (2008/03/10) ---------------- - Added support for comments; expressions are allowed inside comments, i.e. Comments are always included. 0.7 (2008/02/24) ---------------- - Added support for text templates; these allow expression interpolation in non-XML documents like CSS stylesheets and javascript files. 0.5 (2008/02/23) ---------------- - Expression interpolation implemented. 0.4 (2008/02/22) ---------------- - Engine now uses cStringIO yielding a 2.5x performance improvement. Unicode is now handled correctly. 0.3 (2007/12/23) ---------------- - Code optimization; bug fixing spree - Added ``ViewPageTemplateFile`` class - Added support for i18n - Engine rewrite; improved code generation abstractions 0.2 (2007/12/05) ---------------- - Major optimizations to the generated code 0.1 (2007/12/03) ---------------- - First public release Platform: UNKNOWN Classifier: Programming Language :: Python Classifier: Topic :: Text Processing :: Markup :: HTML Classifier: Topic :: Text Processing :: Markup :: XML z3c.pt-2.2.3/docs/0000755000175000001440000000000011762105444014224 5ustar mborchusers00000000000000z3c.pt-2.2.3/docs/Makefile0000644000175000001440000000434711436764405015702 0ustar mborchusers00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = ../bin/sphinx-build PAPER = # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d .build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html web pickle htmlhelp latex changes linkcheck help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " pickle to make pickle files (usable by e.g. sphinx-web)" @echo " htmlhelp to make HTML files and a HTML help project" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " changes to make an overview over all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" clean: -rm -rf .build/* html: mkdir -p .build/html .build/doctrees $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) .build/html @echo @echo "Build finished. The HTML pages are in .build/html." pickle: mkdir -p .build/pickle .build/doctrees $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) .build/pickle @echo @echo "Build finished; now you can process the pickle files or run" @echo " sphinx-web .build/pickle" @echo "to start the sphinx-web server." web: pickle htmlhelp: mkdir -p .build/htmlhelp .build/doctrees $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) .build/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in .build/htmlhelp." latex: mkdir -p .build/latex .build/doctrees $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) .build/latex @echo @echo "Build finished; the LaTeX files are in .build/latex." @echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \ "run these through (pdf)latex." changes: mkdir -p .build/changes .build/doctrees $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) .build/changes @echo @echo "The overview file is in .build/changes." linkcheck: mkdir -p .build/linkcheck .build/doctrees $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) .build/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in .build/linkcheck/output.txt." z3c.pt-2.2.3/docs/index.rst0000644000175000001440000000365711436764405016106 0ustar mborchusers00000000000000.. _index: ====== z3c.pt ====== This package provides a fast implementation of the Zope Page Templates (ZPT) language which aims to be fully compatible with the reference implementation. The template engine is based on Chameleon. .. note:: If you're looking to use Chameleon outside a Zope 2 or 3 environment, the `chameleon.zpt `_ package provides a light-weight implementation of the ZPT language. Zope Page Templates (ZPT) is a system which can generate HTML and XML. ZPT is formed by the *Template Attribute Language* (*TAL*), the *Expression Syntax* (*TALES*), *Intertionalization* (*I18N*) and the *Macro Expansion Template Attribute Language* (*METAL*). The package also implementation a text-mode which supports non-structural content like JavaScript. Language Reference ================== For a general reference, see the `documentation `_ for the :mod:`chameleon.zpt` package. In the present reference, the language details that are specific to this implementation are described. .. toctree:: :maxdepth: 2 narr/tales narr/i18n API documentation ================= :mod:`z3c.pt` API documentation. .. toctree:: :maxdepth: 2 api Support and Development ======================= This package is developed and maintained by `Malthe Borch `_ and the Zope Community. To report bugs, use the `bug tracker `_. If you've got questions that aren't answered by this documentation, please contact the `maillist `_. Browse and check out tagged and trunk versions of :mod:`z3c.pt` via the `Subversion repository `_. To check out the trunk via Subversion, use this command:: svn co svn://svn.zope.org/repos/main/z3c.pt/trunk z3c.pt Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` z3c.pt-2.2.3/docs/api.rst0000644000175000001440000000124311436764405015535 0ustar mborchusers00000000000000.. _pagetemplate_api_module: :mod:`z3c.pt.pagetemplate` -------------------------- ``PageTemplate*`` constructors create templates from XML files. .. automodule:: z3c.pt.pagetemplate .. autoclass:: PageTemplate .. autoclass:: PageTemplateFile :mod:`z3c.pt.texttemplate` -------------------------- ``TextTemplate*`` constructors create templates from plaintext files. .. automodule:: z3c.pt.texttemplate .. autoclass:: TextTemplate .. autoclass:: TextTemplateFile :mod:`z3c.pt.loader` -------------------------- A template loader class is provided (for use with Pylons and other platforms). .. automodule:: z3c.pt.loader .. autoclass:: TemplateLoaderz3c.pt-2.2.3/docs/conf.py0000644000175000001440000001252411436764405015535 0ustar mborchusers00000000000000# -*- coding: utf-8 -*- # # z3c.pt documentation build configuration file, created by # sphinx-quickstart on Wed Jul 16 13:18:14 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest'] # Add any paths that contain templates here, relative to this directory. templates_path = ['.templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General substitutions. project = 'z3c.pt' copyright = '2007-2009 The Zope Community' # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0b14' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # List of directories, relative to source directories, that shouldn't be searched # for source files. #exclude_dirs = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (within the static path) to place at the top of # the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['.static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, the reST sources are included in the HTML build as _sources/. #html_copy_source = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'z3cptdoc' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). latex_documents = [ ('index', 'z3cpt.tex', 'z3c.pt Documentation', 'Malthe Borch', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True z3c.pt-2.2.3/docs/narr/0000755000175000001440000000000011762105444015166 5ustar mborchusers00000000000000z3c.pt-2.2.3/docs/narr/i18n.rst0000644000175000001440000000056011436764405016506 0ustar mborchusers00000000000000.. _i18n_chapter: Internationalization ==================== Language negotation ------------------- Unless a ``target_language`` keyword argument is passed to the render-method of the template, an attempt to negotiate the language using ``zope.i18n.negotiate`` is made. Consult the documentation of :mod:`zope.i18n` to learn how to implement a language negotiator.z3c.pt-2.2.3/docs/narr/tales.rst0000644000175000001440000002402711436764405017043 0ustar mborchusers00000000000000.. _tales_chapter: TALES Expressions ================= The *Template Attribute Language Expression Syntax* (TALES) standard describes expressions that supply :term:`TAL` and :term:`METAL` with data. TALES is *one* possible expression syntax for these languages, but they are not bound to this definition. Similarly, TALES could be used in a context having nothing to do with TAL or METAL. .. note:: The TALES expression components used by the reference implementation are incompatible with :mod:`z3c.pt` and will not work. This :mod:`z3c.pt` package provides its own implementations. TALES expressions are described below with any delimiter or quote markup from higher language layers removed. Here is the basic definition of TALES syntax:: Expression ::= [type_prefix ':'] String type_prefix ::= Name Here are some simple examples:: a.b.c a/b/c nothing python: 1 + 2 string:Hello, ${user/getUserName} The optional *type prefix* determines the semantics and syntax of the *expression string* that follows it. A given implementation of TALES can define any number of expression types, with whatever syntax you like. It also determines which expression type is indicated by omitting the prefix. These are the TALES expression types supported by :mod:`z3c.pt`: * ``python`` - execute a Python expression * ``path`` - locate a value by its "path" (via getattr and getitem) * ``nocall`` - locate an object by its path. * ``not`` - negate an expression * ``string`` - format a string .. note:: if you do not specify a prefix within an expression context, :mod:`z3c.pt`` assumes that the expression is a *path* expression. .. _tales_built_in_names: Built-in Names -------------- In addition to ``template``, ``macros``, ``default`` and ``repeat``, the following names are always available to TALES expressions in :mod:`z3c.pt`: - ``nothing`` - equal to the Python null-value ``None``. The following names are available in TALES expressions when evaluated inside page templates: - ``options`` - contains the keyword arguments passed to the render-method. - ``context`` - the template context - ``request`` - the current request - ``path`` - a method which will evaluate a path-expression, expressed as a string. - ``exists`` - a method which will evaluate an exists-expression, expressed as a string. - ``modules`` - provides access to previously imported system modules; using this variable is not recommended. - ``econtext`` - dynamic variable scope dictionary which keeps track of global variables brought into scope using macros; used internally by the engine, relying on this variable is not recommended (although some legacy applications do so). Finally, view page templates provide the following names: - ``view`` - the view instance ``nocall`` expressions ---------------------- Syntax ~~~~~~ ``nocall`` expression syntax:: nocall_expression ::= 'nocall:' path_expression Description ~~~~~~~~~~~ Nocall expressions avoid calling the __call__ method of the last element of a path expression. An ordinary path expression tries to render the object that it fetches. This means that if the object is a function, method, or some other kind of executable thing, then expression will evaluate to the result of calling the object. This is usually what you want, but not always. Examples ~~~~~~~~ Using nocall to prevent calling the ``__call__`` of the last element of a path expression:: Id: Title ``not`` expressions ------------------- Syntax ~~~~~~ ``not`` expression syntax:: not_expression ::= 'not:' expression Description ~~~~~~~~~~~ A ``not`` expression evaluates the expression string (recursively) as a full expression, and returns the boolean negation of its value. If the expression supplied does not evaluate to a boolean value, *not* will issue a warning and *coerce* the expression's value into a boolean type based on the following rules: #. the number 0 is *false* #. positive and negative numbers are *true* #. an empty string or other sequence is *false* #. a non-empty string or other sequence is *true* #. a *non-value* (e.g. None) is *false* #. all other values are implementation-dependent. If no expression string is supplied, an error should be generated. :mod:`z3c.pt` considers all objects not specifically listed above as *false* to be *true*. Examples ~~~~~~~~ Testing a sequence::

There are no keys.

``path`` expressions -------------------- Syntax ~~~~~~ Path expression syntax:: PathExpr ::= Path [ '|' Expression ] Path ::= variable [ '/' PathSegment ]* variable ::= Name PathSegment ::= ( '?' variable ) | PathChar+ PathChar ::= AlphaNumeric | ' ' | '_' | '-' | '.' | ',' | '~' Description ~~~~~~~~~~~ A path expression consists of a *path* optionally followed by a vertical bar (|) and alternate expression. A path consists of one or more non-empty strings separated by slashes. The first string must be a variable name (a built-in variable or a user defined variable), and the remaining strings, the *path segments*, may contain letters, digits, spaces, and the punctuation characters underscore, dash, period, comma, and tilde. A limited amount of indirection is possible by using a variable name prefixed with ``?`` as a path segment. The variable must contain a string, which replaces that segment before the path is traversed. For example:: request/cookies/oatmeal nothing here/some-file 2001_02.html.tar.gz/foo root/to/branch | default request/name | string:Anonymous Coward here/?tname/macros/?mname When a path expression is evaluated, :mod:`z3c.pt` attempts to traverse the path, from left to right, until it succeeds or runs out of paths segments. To traverse a path, it first fetches the object stored in the variable. For each path segment, it traverses from the current object to the subobject named by the path segment. Subobjects are located according to standard traversal rules. .. note:: The Zope 3 traversal API is used to traverse to subobjects. The `five.pt `_ package provides a Zope 2-compatible path expression. Once a path has been successfully traversed, the resulting object is the value of the expression. If it is a callable object, such as a method or template, it is called. If a traversal step fails, and no alternate expression has been specified, an error results. Otherwise, the alternate expression is evaluated. The alternate expression can be any TALES expression. For example, ``request/name | string:Anonymous Coward`` is a valid path expression. This is useful chiefly for providing default values, such as strings and numbers, which are not expressable as path expressions. Since the alternate expression can be a path expression, it is possible to "chain" path expressions, as in ``first | second | third | nothing``. If no path is given the result is *nothing*. Since every path must start with a variable name, you need a set of starting variables that you can use to find other objects and values. See the :ref:`tales_built_in_names` for a list of built-in variables. Variable names are looked up first in locals, then in the built-in list, so the built-in variables act just like built-ins in Python; They are always available, but they can be shadowed by a local variable declaration. Examples ~~~~~~~~ Inserting a cookie variable or a property:: preference Inserting the user name::

User name

``python`` expressions ---------------------- Syntax ~~~~~~ Python expression syntax:: Any valid Python language expression Description ~~~~~~~~~~~ Python expressions evaluate Python code in a restricted environment (no access to variables starting with an underscore). Python expressions offer the same facilities as those available in Python-based Scripts and DTML variable expressions. .. warning: Zope 2 page templates may be executed in a security-restricted environment which ties in with the Zope 2 security model. This is not supported by :mod:`z3c.pt`. Examples ~~~~~~~~ Using a module usage (pick a random choice from a list):: A random number between one and five String processing (capitalize the user name)::

User Name

Basic math (convert an image size to megabytes)::

12.2323

String formatting (format a float to two decimal places)::

13.56

``string`` expressions ---------------------- Syntax ~~~~~~ String expression syntax:: string_expression ::= ( plain_string | [ varsub ] )* varsub ::= ( '$' Path ) | ( '${' Path '}' ) plain_string ::= ( '$$' | non_dollar )* non_dollar ::= any character except '$' Description ~~~~~~~~~~~ String expressions interpret the expression string as text. If no expression string is supplied the resulting string is *empty*. The string can contain variable substitutions of the form ``$name`` or ``${path}``, where ``name`` is a variable name, and ``path`` is a path expression. The escaped string value of the path expression is inserted into the string. .. note:: To prevent a ``$`` from being interpreted this way, it must be escaped as ``$$``. Examples ~~~~~~~~ Basic string formatting:: Spam and Eggs Using paths::

total: 12

Including a dollar sign::

cost: $42.00

z3c.pt-2.2.3/src/0000755000175000001440000000000011762105444014063 5ustar mborchusers00000000000000z3c.pt-2.2.3/src/z3c.pt.egg-info/0000755000175000001440000000000011762105444016676 5ustar mborchusers00000000000000z3c.pt-2.2.3/src/z3c.pt.egg-info/SOURCES.txt0000644000175000001440000000203611762105440020557 0ustar mborchusers00000000000000AUTHOR.txt CHANGES.txt CONTRIBUTORS.txt COPYRIGHT.txt LICENSE.txt README.txt bootstrap.py buildout.cfg setup.py docs/Makefile docs/api.rst docs/conf.py docs/index.rst docs/narr/i18n.rst docs/narr/tales.rst src/z3c/__init__.py src/z3c.pt.egg-info/PKG-INFO src/z3c.pt.egg-info/SOURCES.txt src/z3c.pt.egg-info/dependency_links.txt src/z3c.pt.egg-info/namespace_packages.txt src/z3c.pt.egg-info/not-zip-safe src/z3c.pt.egg-info/requires.txt src/z3c.pt.egg-info/top_level.txt src/z3c/pt/README.txt src/z3c/pt/__init__.py src/z3c/pt/configure.zcml src/z3c/pt/expressions.py src/z3c/pt/loader.py src/z3c/pt/namespaces.py src/z3c/pt/pagetemplate.py src/z3c/pt/tests/__init__.py src/z3c/pt/tests/boolean.pt src/z3c/pt/tests/exists.pt src/z3c/pt/tests/false.pt src/z3c/pt/tests/function_namespaces.pt src/z3c/pt/tests/helloworld.pt src/z3c/pt/tests/nocall.pt src/z3c/pt/tests/path.pt src/z3c/pt/tests/provider.pt src/z3c/pt/tests/test_doctests.py src/z3c/pt/tests/test_loader.py src/z3c/pt/tests/test_templates.py src/z3c/pt/tests/view.css src/z3c/pt/tests/view.ptz3c.pt-2.2.3/src/z3c.pt.egg-info/not-zip-safe0000644000175000001440000000000111436766546021142 0ustar mborchusers00000000000000 z3c.pt-2.2.3/src/z3c.pt.egg-info/PKG-INFO0000644000175000001440000010603711762105440017776 0ustar mborchusers00000000000000Metadata-Version: 1.1 Name: z3c.pt Version: 2.2.3 Summary: Fast ZPT engine. Home-page: UNKNOWN Author: Malthe Borch and the Zope Community Author-email: zope-dev@zope.org License: ZPL Description: Overview ======== This is a fast implementation of the ZPT template engine for Zope 3 which uses Chameleon to compile templates to byte-code. The package provides application support equivalent to ``zope.app.pagetemplate``. For usage, see the README.txt file inside the package. Changelog ========= 2.2.3 (2012-06-01) ~~~~~~~~~~~~~~~~~~ Compatibility: - The translation function now accepts (but ignores) a ``context`` argument. This fixes a compatibility issue with Chameleon 2.9.x. 2.2.2 (2012-04-24) ~~~~~~~~~~~~~~~~~~ Bugfixes: - Do not rely on the "LANGUAGE" request key to skip language negotiation. Instead, we assume that negotiation is cheap (and probably cached). 2.2.1 (2012-02-15) ~~~~~~~~~~~~~~~~~~ - Only require Chameleon >= 2.4, was needlessly bumped in last release. - Add test extra, remove versions from buildout.cfg. 2.2 (2012-01-08) ~~~~~~~~~~~~~~~~ Features: - Whitespace between attributes is now reduced to a single whitespace character. - The ``request`` symbol is no longer required to evaluate a path expression; it now defaults to ``None`` if not present in the namespace. Bugfixes: - The content provider expression now correctly applies TAL namespace data. Changes: - The ``ZopeTraverser`` class has been removed and replaced with a simple function. 2.1.5 (2011-11-24) ~~~~~~~~~~~~~~~~~~ - Use non-strict mode if available for compatibility with the reference engine where expressions are only compiled at evaluation time. 2.1.4 (2011-09-14) ~~~~~~~~~~~~~~~~~~ - The provider expression is now first evaluated as a string expression, the result of which is used as the content provider name. This fixes an issue where (provider-) string expressions would not get evaluated correctly, e.g. ``provider: ${mgr}``. 2.1.3 (2011-08-22) ~~~~~~~~~~~~~~~~~~ - Configure HTML boolean attributes (in HTML-mode only):: "compact", "nowrap", "ismap", "declare", "noshade", "checked", "disabled", "readonly", "multiple", "selected", "noresize", "defer" 2.1.2 (2011-08-19) ~~~~~~~~~~~~~~~~~~ - Enable option ``literal_false`` to get the behavior that a value of ``False`` does not drop an attribute. 2.1.1 (2011-08-11) ~~~~~~~~~~~~~~~~~~ - Make sure the builtin names 'path' and 'exists' can be redefined. - Guard ``sys.modules`` (mapped to the builtin variable "modules") against import-time side effects using ``ProxyFactory``. 2.1 (2011-07-28) ~~~~~~~~~~~~~~~~ - Use dynamic expression evaluation framework that comes included with Chameleon. 2.0 (2011-07-14) ~~~~~~~~~~~~~~~~ - Point release. - Move implementation-specific context setup to ``render`` method. This allows use of template class with an already prepared context. - Fixed issue with the call flag on the Zope traverser compiler. 2.0-rc3 (2011-07-11) ~~~~~~~~~~~~~~~~~~~~ - Python-expressions are no longer TALES-expressions; previously, the pipe operator would split Python expression clauses, allowing fallbacks even for Python expressions, but this is not the standard behavior of ZPT. - Fixed an issue where an error which occurred inside a dynamic ``path`` or ``exists`` evaluation would fail to propagate due to a missing remote context. - Set variables ``here`` and ``context`` to the bound instance value on ``PageTemplate`` instances. 2.0-rc2 (2011-03-24) ~~~~~~~~~~~~~~~~~~~~ - Fixed an issue with ``"exists:"`` expression where a callable would be attempted called. It is meanwhile implied with this expression types that it should use the ``"nocall:"`` pragma. 2.0-rc1 (2011-02-28) ~~~~~~~~~~~~~~~~~~~~ - Update to Chameleon 2.0. This release includes many changes and is a complete rewrite of the 1.x series. Platform: * Python 2.5+ now required. Notable changes: * Expression interpolation is always enabled. * Whitespace output is different, now closely aligned to the template input. * New language constructs: 1) tal:on-error 2) tal:switch 3) tal:case Incompatibilities: * The expression translation interface has been replaced with an expression engine. This means that all expressions must be rewritten. - The exists expression evaluator should ignore KeyError exceptions as well. - Special-case handling of Zope2's Missing.MV as used by Products.ZCatalog for LP#649343. [rossp] 1.2.1 (2010/05/13) ------------------ - Bind template to the template object in the general case. 1.2 (2010/05/12) ------------------ - Fixed compatibility issue with recent change in Chameleon. - Fixed regression introduced with ``args`` being passed in. Incidentally, the name ``args`` was used as the star argument name. - Look at language set on request before invoking the zope.i18n negotiator. This makes i18n work again on Zope2. 1.1.1 (2010/04/06) ------------------ - Fixed issue where arguments were not passed on to template as ``args``. 1.1.0 (2010/01/09) ------------------ - Update to combined Chameleon distribution. 1.0.1 (2009/07/06) ------------------ - Bind translation context (request) to translation method. Although not required in newer versions of the translation machinery, some versions will ask for a translation context in order to negotiate language even when a language is explicitly passed in. - Declare zope security settings for classes when zope.security is present as the "class" ZCML directive was moved there. 1.0.0 (2009/07/06) ------------------ - First point release. 1.0b17 (2009/06/14) ------------------- - Made the Zope security declaration for the repeat dictionary be conditional on the presence of zope.app.security instead of zope.app.component. 1.0b16 (2009/05/20) ------------------- - Updated run-time expression evaluator method to work after a recent architectural change in Chameleon. [malthe] - Check that we have a non-trivial response-object before trying to set the content type. [malthe] - Wrap ``sys.modules`` dictionary in an "opaque" dictionary class, such that the representation string does not list all loaded modules. [malthe] 1.0b15 (2009/04/24) ------------------- - Removed lxml extra, as we do no longer depend on it. [malthe] - Make sure the path expression is a simple string, not unicode. [malthe] - Detect path prefix properly for ViewPageTemplateFile usage in doctests. [sidnei] - The ``template`` symbol is already set by the template base class. [malthe] - Set Content-Type header, for backwards compatibility with zope.app.pagetemplate. [sidnei] 1.0b14 (2009/03/31) ------------------- - Updated language adapter to work with 'structure' meta attribute. [malthe] 1.0b13 (2009/03/23) ------------------- - When traversing on dictionaries, only exposes dictionary items (never attributes); this is to avoid ambiguity. [sidnei, malthe] - Path expressions need to pass further path items in reverse order to traversePathElement, because that's what it expects. [sidnei] 1.0b12 (2009/03/09) ------------------- - Insert initial variable context into dynamic scope. The presence of these is expected by many application. [malthe] 1.0b11 (2009/03/05) ------------------- - If a namespace-acquired object provides ``ITraversable``, use path traversal. [malthe] - Implemented TALES function namespaces. [sidnei, malthe] - Catch ``NameError`` in exists-traverser (return false). [malthe] - Catch ``NameError`` in exists-evaluator (return false). [malthe] - If the supplied ``context`` and ``request`` parameters are trivial, get them from the view instance. [malthe] - Expressions in text templates are never escaped. [malthe] - Do not bind template to a trivial instance. [malthe] 1.0b10 (2009/02/24) ------------------- - Fixed exists-traverser such that it always returns a boolean value. [malthe] 1.0b9 (2009/02/19) ------------------ - When evaluating path-expressions at runtime (e.g. the ``path`` method), run the source through the transform first to support dynamic scope. [malthe] 1.0b8 (2009/02/17) ------------------ - Allow attribute access to ``__call__`` method on bound page templates. [malthe] 1.0b7 (2009/02/13) ------------------ - Fixed issue where symbol mapping would not be carried through under a negation (not). [malthe] - Optimize simple case: if path expression is a single path and path is 'nothing' or has 'nocall:', just return value as-is, without going through path_traverse. [sidnei] - Moved evaluate_path and evaluate_exists over from ``five.pt``, adds support for global ``path()`` and ``exists()`` functions for use in ``python:`` expressions (LP #317967). - Added Zope security declaration for the repeat dictionary (tales iterator). [malthe] 1.0b6 (2008/12/18) ------------------ - The 'not' pragma acts recursively. [malthe] 1.0b5 (2008/12/15) ------------------ - View templates now support argument-passing for alternative context and request (for compatibility with ``zope.app.pagetemplate``). [malthe] - Switched off the $-interpolation feature per default; It may be activated on a per-template basis using ``meta:interpolation='true'``. [seletz] - Allow more flexibility in overriding the PathTranslator method. [hannosch] - Removed the forced defaultencoding from the benchmark suite. [hannosch] 1.0b4 (2008/11/19) ------------------ - Split out content provider function call to allow modification through subclassing. [malthe] - Added language negotiation. [malthe] - Simplified template class inheritance. [malthe] - Added support for the question-mark operator in path-expressions. [malthe] - Updated expressions to recent API changes. [malthe] - Added 'exists' and 'not' translators. [malthe] Bug fixes - Adjusted the bigtable benchmark test to API changes. [hannosch] 1.0b3 (2008/11/12) ------------------ - Added ``PageTemplate`` and ``PageTemplateFile`` classes. [malthe] 1.0b2 (2008/11/03) ------------------ Bug fixes - Allow '.' character in content provider expressions. - Allow '+' character in path-expressions. 1.0b1 (2008/10/02) ------------------ Package changes - Split out compiler to "Chameleon" package. [malthe] Backwards incompatibilities - Moved contents of ``z3c.pt.macro`` module into ``z3c.pt.template``. [malthe] - Namespace attribute "xmlns" no longer rendered for templates with no explicit document type. [malthe] - Changes to template method signatures. [malthe] - Engine now expects all strings to be unicode or contain ASCII characters only, unless an encoding is provided. [malthe] - The default path traverser no longer proxies objects. [malthe] - Template output is now always converted to unicode. [malthe] - The ``ViewPageTemplateFile`` class now uses 'path' as the default expression type. [malthe] - The compiler now expects an instantiated parser instance. [malthe] Features - Added expression translator "provider:" (which renders a content provider as defined in the ``zope.contentprovider`` package). [malthe] - Added template API to render macros. [malthe] - Optimized template loader so only a single template is instantiated per file. [malthe] - Made ``z3c.pt`` a namespace package. [malthe] - Added reduce and restore operation to the compilation and rendering flow in the test examples to verify integrity. [malthe] - The ZPT parser now supports prefixed native attributes, e.g. . [malthe] - Source-code is now written to disk in debug mode. [malthe] - Custom validation error is now raised if inserted string does not validate (when debug mode is enabled). [malthe] - Added support for omitting rendering of HTML "toggle" attributes (option's ``selected`` and input's ``checked``) within dynamic attribute assignment. If the value of the expression in the assignment evaluates equal to boolean False, the attribute will not be rendered. If the value of the expression in the assignment evaluates equal to boolean True, the attribute will be rendered and the value of the attribute will be the value returned by the expression. [chrism] - XML namespace attribute is now always printed for root tag. [malthe] - Allow standard HTML entities. [malthe] - Added compiler option to specify an implicit doctype; this is currently used by the template classes to let the loose XHTML doctype be the default. [malthe] - Added support for translation of tag body. [malthe] - Added security configuration for the TALES iterator (repeat dictionary). This is made conditional on the availability of the application security framework. [malthe] - Dynamic attributes are now ordered as they appear in the template. [malthe] - Added ``symbol_mapping`` attribute to code streams such that function dependencies can be registered at compile-time. [malthe] - Allow BaseTemplate-derived classes (PageTemplate, PageTemplateFile, et. al) to accept a ``doctype`` argument, which will override the doctype supplied by the source of the template if specified. [chrism] - Language negotiation is left to the page template superclass, so we don't need to pass in a translation context anymore. [malthe] - The ``ViewPageTemplateFile`` class now uses the module path of the calling class to get an absolute path to a relative filename passed to the constructor. [malthe] - Added limited support for the XInclude ``include`` directive. The implemented subset corresponds to the Genshi implementation, except Match-templates, which are not made available to the calling template. [malthe] - Use a global template registry for templates on the file-system. This makes it inexpensive to have multiple template class instances pointing to the same file. [malthe] - Reimplemented the disk cache to correctly restore all template data. This implementation keeps a cache in a pickled format in a file next to the original template. [malthe] - Refactored compilation classes to better separate concerns. [malthe] - Genshi macros (py:def) are now available globally. [malthe] - A syntax error is now raised when an interpolation expression is not exhausted, e.g. only a part of the string is a valid Python-expression. [malthe] - System variables are now defined in a configuration class. [malthe] - Improve performance of codegen by not repeatedly calling an expensive "flatten" function. [chrism] - Remove ``safe_render`` implementation detail. It hid information in tracebacks. [chrism] - Implemented TAL global defines. [malthe] - Added support for variables with global scope. [malthe] - Curly braces may now be omitted in an expression interpolation if the expression is just a variable name; this complies with the Genshi syntax. [malthe] - UTF-8 encode Unicode attribute literals. [chrism] - Substantially reduced compiler overhead for lxml CDATA workaround. [malthe] - Split out element compiler classes for Genshi and Zope language dialects. [malthe] - Make lxml a setuptools "extra". To install with lxml support (currently required by Genshi), specify "z3c.pt [lxml]" in any references you need to make to the package in buildout or in setup.py install_requires. [chrism] - Add test-nolxml and py-nolxml parts to buildout so the package's tests can be run without lxml. [chrism] - No longer require default namespace. [malthe] - Changed source code debug mode files to be named .py instead of .source. - Generalized ElementTree-import to allow both Python 2.5's ``xml.etree`` module and the standalone ``ElementTree`` package. [malthe] - Expression results are now validated for XML correctness when the compiler is running in debug-mode. [malthe] - Preliminary support for using ``xml.etree`` as fallback for ``lxml.etree``. [malthe] - String-expressions may now contain semi-colons using a double semi-colon literal (;;). [malthe] - Preserve CDATA sections. [malthe] - Get rid of package-relative magic in constructor of BaseTemplateFile in favor of just requiring an absolute path or a path relative to getcwd(). Rationale: it didn't work when called from __main__ when the template was relative to getcwd(), which is the 99% case for people first trying it out. [chrism] - Added support for METAL. [malthe] - Add a TemplateLoader class to have a convenient method to instantiate templates. This is similar to the template loaders from other template toolkits and makes integration with Pylons a lot simpler. [wichert] - Switch from hardcoding all options in config.py to using parameters for the template. This also allows us to use the more logical auto_reload flag instead of reusing PROD_MODE, which is also used for other purposes. [wichert] - Treat comments, processing instructions, and named entities in the source template as "literals", which will be rendered into the output unchanged. [chrism] Bugfixes - Skip elements in a "define-slot" clause if its being filled by the calling template. [malthe] - Support "fill-slot" on elements with METAL namespace. [malthe] - Omit element text when rendering macro. [malthe] - ``Macros`` class should not return callable functions, but rather a ``Macro`` object, which has a ``render``-method. This makes it possible to use a path-expression to get to a macro without calling it. [malthe] - Fixed bug where a repeat-clause would reset the repeat variable before evaluating the expression. [malthe] - Fixed an issue related to correct restoring of ghosted template objects. [malthe] - Implicit doctype is correctly reestablished from cache. [malthe] - Remove namespace declaration on root tag to work around syntax error raised when parsing an XML tree loaded from the file cache. [malthe] - Attribute assignments with an expression value that started with the characters ``in`` (e.g. ``info.somename``) would be rendered to the generated Python without the ``in`` prefix (as e.g. ``fo.somename``). [chrism] - When filling METAL slots (possibly with a specific version of libxml2, I am using 2.6.32) it was possible to cause the translator to attempt to add a stringtype to a NoneType (on a line that reads ``variable = self.symbols.slot+element.node.fill_slot`` because an XPath expression looking for fill-slot nodes did not work properly). [chrism] - Preserve whitespace in string translation expressions. [malthe] - Fixed interpolation bug where multiple attributes with interpolation expressions would result in corrupted output. [malthe] - Support try-except operator ('|') when 'python' is the default expression type. [malthe] - METAL macros should render in the template where they're defined. [malthe] - Avoid printing a line-break when we repeat over a single item only. [malthe] - Corrected Genshi namespace (needs a trailing slash). [malthe] - Fixed a few more UnicodeDecodeErrors (test contributed by Wiggy). In particular, never upcast to unicode during transformation, and utf-8 encode Unicode attribute keys and values in Assign expressions (e.g. py:attrs). [chrism] - Fixed off-by-one bug in interpolation routine. [malthe] - The repeat-clause should not output tail with every iteration. [malthe] - CDATA sections are now correctly handled when using the ElementTree-parser. [malthe] - Fixed bug in path-expressions where string instances would be (attempted) called. [malthe] - CDATA sections are now correctly preserved when using expression interpolation. [malthe] - The Genshi interpolation operator ${} should not have its result escaped when used in the text or tail regions. [malthe] - Fixed edge case bug where inserting both a numeric entity and a literal set of unicode bytes into the same document would cause a UnicodeDecodeError. See also http://groups.google.com/group/z3c_pt/browse_thread/thread/aea963d25a1778d0?hl=en [chrism] - Static attributes are now properly overriden by py:attr-attributes. [malthe] 0.9 (2008/08/07) ---------------- - Added support for Genshi-templates. [malthe] - Cleanup and refactoring of translation module. [malthe] - If the template source contains a DOCTYPE declaration, output it during rendering. [chrism] - Fixed an error where numeric entities specified in text or tail portions of elements would cause a UnicodeDecodeError to be raised on systems configured with an 'ascii' default encoding. [chrism] - Refactored file system based cache a bit and added a simple benchmark for the cache. The initial load speed for a template goes down significantly with the cache. Compared to zope.pagetemplate we are only 3x slower, compared to 50x slower when cooking each template on process startup. - Got rid entirely of the _escape function and inlined the actual code instead. We go up again to 12x for path and 19x for Python expressions :) [hannosch] - Avoid string concatenation and use multiple write statements instead. These are faster now, since we use a list append internally. [hannosch] - Inline the _escape function, because function calls are expensive in Python. Added missing escaping for Unicode values. [fschulze, hannosch] - When templates are instantiated outside of a class-definition, a relative file path will be made absolute using the module path. [malthe] - Simplified the _escape function handling by pulling in the str call into the function. Corrected the bigtable hotshot test to only benchmark rendering. - Replaced the cgi.escape function by an optimized local version, we go up to 11x for path and 16x for Python expressions :) In the bigtable benchmark the enhancement is more noticable - we are the same speed as spitfire -O1 templates now and just half the speed of -O3 :)) - Added a new benchmark test called bigtable that produces results which are directly comparable to those produced by the bigtable.py benchmark in the spitfire project. - Introduce a new config option called `Z3C_PT_DISABLE_I18N`. If this environment variable is set to `true`, the template engine will not call into the zope.i18n machinery anymore, but fall back to simple interpolation in all cases. In a normal Zope environment that has the whole i18n infrastructure set up, this will render the templates about 15x faster than normal TAL, instead of only 10x faster at this point. - Removed the `second rendering` tests from the benchmark suite. Since we enable the file cache for the benchmarks, there's no difference between the first and second rendering anymore after the cache file has been written. - Require zope.i18n 3.5 and add support for using its new negotiate function. If you use the `zope_i18n_allowed_languages` environment variable the target language for a template is only negotiated once per template, instead of once for each translate function call. This more than doubles the speed and the benchmark is back at 9.2 times faster. - Extended the i18n handling to respect the passed in translation context to the template. Usually this is the request, which is passed on under the internal name of `_context` into the render functions. After extending the i18n tests to include a negotiator and message catalog the improvement is only at 4.5 anymore, as most of the time is spent inside the i18n machinery. - Added persistent file cache functionality. If the environment variable is set, each file system based template will add a directory to the cache (currently a SHA-1 of the file's absolute path is used as the folder name) and in the folder one file per params for the template (cache filename is the hash of the params). Once a template file is initialized, an instance local registry is added, which then looks up all cached files and pre-populates the registry with the render functions. - Fixed interpolation edge case bugs. [malthe] - Added new `Z3C_PT_FILECACHE` environment variable pointing to a directory. If set, this will be used to cache the compiled files. - Added a second variation of the repeat clause, using a simple for loop. It doesn't support the repeatdict, though and is therefor not used yet. Also began work to add introspection facilities to clauses about the variables being used in them. The simpler loop causes the benchmarks to go up to a 10.5 (old 9.5) for path expressions and 14.5 (12.5) for python expressions. So the next step is to introduce an optimization phase, that can decide which variant of the loops to use. - Made the debug mode independent from the Python debug mode. You can now specify an environment variable called `Z3C_PT_DEBUG` to enable it. - Added some code in a filecache module that can later be used to write out and reload the compiled Python code to and from the file system. We should be able to avoid reparsing on Python process restart. - Simplified the generated _escape code. cgi.escape's second argument is a simple boolean and not a list of characters to quote. - Use a simple list based BufferIO class instead of a cStringIO for the out stream. Avoiding the need to encode Unicode data is a bigger win. We do not support arbitrarily mixing of Unicode and non-ascii inside the engine. - Merged two adjacent writes into one inside the Tag clause. - Applied a bunch of micro-optimizations. ''.join({}) is slightly faster than ''.join({}.keys()) and does the same. Avoid a try/except for error handling in non-debug mode. Test against 'is None' instead of a boolean check for the result of the template registry lookup. Made PROD_MODE available defined as 'not DEBUG_MODE' in config.py, so we avoid the 'not' in every cook-check. - Added more benchmark tests for the file variants. - Optimized 'is None' handling in Tag clause similar to the Write clause. - Made the _out.write method directly available as _write in all scopes, so we avoid the method lookup call each time. - Optimized 'is None' handling in Write clause. - Slightly refactored benchmark tests and added tests for the file variants. - In debug mode the actual source code for file templates is written out to a .source file, to make it easier to inspect it. - Make debug mode setting explicit in a config.py. Currently it is bound to Python's __debug__, which is False when run with -O and otherwise True. - Use a simplified UnicodeWrite clause for the result of _translate calls, as the result value is guaranteed to be Unicode. - Added benchmark tests for i18n handling. - Added more tests for i18n attributes handling. - Don't generate empty mappings for expressions with a trailing semicolon. - Fixed undefined name 'static' error in i18n attributes handling and added quoting to i18n attributes. - Added condition to the valid attributes on tags in the tal namespace. - Made sure the traceback from the *first* template exception is carried over to __traceback_info__ - Added template source annotations on exceptions raised while rendering a template. 0.8 (2008/03/19) ---------------- - Added support for 'nocall' and 'not' (for path-expressions). - Added support for path- and string-expressions. - Abstracted expression translation engine. Expression implementations are now pluggable. Expression name pragmas are supported throughout. - Formalized expression types - Added support for 'structure'-keyword for replace and content. - Result of 'replace' and 'content' is now escaped by default. - Benchmark is now built as a custom testrunner 0.7 (2008/03/10) ---------------- - Added support for comments; expressions are allowed inside comments, i.e. Comments are always included. 0.7 (2008/02/24) ---------------- - Added support for text templates; these allow expression interpolation in non-XML documents like CSS stylesheets and javascript files. 0.5 (2008/02/23) ---------------- - Expression interpolation implemented. 0.4 (2008/02/22) ---------------- - Engine now uses cStringIO yielding a 2.5x performance improvement. Unicode is now handled correctly. 0.3 (2007/12/23) ---------------- - Code optimization; bug fixing spree - Added ``ViewPageTemplateFile`` class - Added support for i18n - Engine rewrite; improved code generation abstractions 0.2 (2007/12/05) ---------------- - Major optimizations to the generated code 0.1 (2007/12/03) ---------------- - First public release Platform: UNKNOWN Classifier: Programming Language :: Python Classifier: Topic :: Text Processing :: Markup :: HTML Classifier: Topic :: Text Processing :: Markup :: XML z3c.pt-2.2.3/src/z3c.pt.egg-info/top_level.txt0000644000175000001440000000000411762105440021416 0ustar mborchusers00000000000000z3c z3c.pt-2.2.3/src/z3c.pt.egg-info/requires.txt0000644000175000001440000000020411762105440021266 0ustar mborchusers00000000000000setuptools zope.interface zope.component zope.i18n >= 3.5 zope.traversing zope.contentprovider Chameleon >= 2.4 [test] zope.testingz3c.pt-2.2.3/src/z3c.pt.egg-info/dependency_links.txt0000644000175000001440000000000111762105440022740 0ustar mborchusers00000000000000 z3c.pt-2.2.3/src/z3c.pt.egg-info/namespace_packages.txt0000644000175000001440000000000411762105440023217 0ustar mborchusers00000000000000z3c z3c.pt-2.2.3/src/z3c/0000755000175000001440000000000011762105444014562 5ustar mborchusers00000000000000z3c.pt-2.2.3/src/z3c/pt/0000755000175000001440000000000011762105444015205 5ustar mborchusers00000000000000z3c.pt-2.2.3/src/z3c/pt/expressions.py0000644000175000001440000001655311702340244020144 0ustar mborchusers00000000000000import re import ast import namespaces import zope.event from zope.traversing.adapters import traversePathElement from zope.contentprovider.interfaces import IContentProvider from zope.contentprovider.interfaces import ContentProviderLookupError from zope.contentprovider.tales import addTALNamespaceData from zope.traversing.interfaces import ITraversable from zope.location.interfaces import ILocation try: from zope.contentprovider.interfaces import BeforeUpdateEvent except ImportError: BeforeUpdateEvent = None from types import MethodType from chameleon.tales import TalesExpr from chameleon.tales import ExistsExpr as BaseExistsExpr from chameleon.tales import PythonExpr as BasePythonExpr from chameleon.tales import StringExpr from chameleon.codegen import template from chameleon.astutil import load from chameleon.astutil import Symbol from chameleon.astutil import Builtin from chameleon.astutil import NameLookupRewriteVisitor from chameleon.exc import ExpressionError _marker = object() def render_content_provider(econtext, name): name = name.strip() context = econtext.get('context') request = econtext.get('request') view = econtext.get('view') cp = zope.component.queryMultiAdapter( (context, request, view), IContentProvider, name=name) # provide a useful error message, if the provider was not found. if cp is None: raise ContentProviderLookupError(name) # add the __name__ attribute if it implements ILocation if ILocation.providedBy(cp): cp.__name__ = name # Insert the data gotten from the context addTALNamespaceData(cp, econtext) # Stage 1: Do the state update. if BeforeUpdateEvent is not None: zope.event.notify(BeforeUpdateEvent(cp, request)) cp.update() # Stage 2: Render the HTML content. return cp.render() def path_traverse(base, econtext, call, path_items): if path_items: request = econtext.get('request') path_items = list(path_items) path_items.reverse() while len(path_items): name = path_items.pop() ns_used = ':' in name if ns_used: namespace, name = name.split(':', 1) base = namespaces.function_namespaces[namespace](base) if ITraversable.providedBy(base): base = traversePathElement( base, name, path_items, request=request) # base = proxify(base) continue # special-case dicts for performance reasons if isinstance(base, dict): next = base.get(name, _marker) else: next = getattr(base, name, _marker) if next is not _marker: base = next if ns_used and isinstance(base, MethodType): base = base() continue else: base = traversePathElement( base, name, path_items, request=request) # if not isinstance(base, (basestring, tuple, list)): # base = proxify(base) if call and getattr(base, '__call__', _marker) is not _marker: return base() return base class ContextExpressionMixin(object): """Mixin-class for expression compilers.""" transform = None def __call__(self, target, engine): # Make call to superclass to assign value to target assignment = super(ContextExpressionMixin, self).\ __call__(target, engine) transform = template( "target = transform(econtext, target)", target=target, transform=self.transform, ) return assignment + transform class PathExpr(TalesExpr): path_regex = re.compile( r'^(?:(nocall|not):\s*)*((?:[A-Za-z_][A-Za-z0-9_:]*)' + r'(?:/[?A-Za-z_@\-+][?A-Za-z0-9_@\-\.+/:]*)*)$') interpolation_regex = re.compile( r'\?[A-Za-z][A-Za-z0-9_]+') traverser = Symbol(path_traverse) def translate(self, string, target): """ >>> from chameleon.tales import test >>> test(PathExpr('')) is None True """ string = string.strip() if not string: return template("target = None", target=target) m = self.path_regex.match(string) if m is None: raise ExpressionError("Not a valid path-expression.", string) nocall, path = m.groups() # note that unicode paths are not allowed parts = str(path).split('/') components = [] for part in parts[1:]: interpolation_args = [] def replace(match): start, end = match.span() interpolation_args.append( part[start + 1:end]) return "%s" while True: part, count = self.interpolation_regex.subn(replace, part) if count == 0: break if len(interpolation_args): component = template( "format % args", format=ast.Str(part), args=ast.Tuple( list(map(load, interpolation_args)), ast.Load() ), mode="eval") else: component = ast.Str(part) components.append(component) base = parts[0] if not components: if len(parts) == 1 and (nocall or base == 'None'): return template("target = base", base=base, target=target) else: components = () call = template( "traverse(base, econtext, call, path_items)", traverse=self.traverser, base=load(base), call=load(str(not nocall)), path_items=ast.Tuple(elts=components), mode="eval", ) return template("target = value", target=target, value=call) class NocallExpr(PathExpr): """A path-expression which does not call the resolved object.""" def translate(self, expression, engine): return super(NocallExpr, self).translate( "nocall:%s" % expression, engine) class ExistsExpr(BaseExistsExpr): exceptions = AttributeError, LookupError, TypeError, KeyError, NameError def __init__(self, expression): super(ExistsExpr, self).__init__("nocall:" + expression) class ProviderExpr(ContextExpressionMixin, StringExpr): transform = Symbol(render_content_provider) class PythonExpr(BasePythonExpr): builtins = dict( (name, template( "tales(econtext, rcontext, name)", tales=Builtin("tales"), name=ast.Str(s=name), mode="eval")) for name in ('path', 'exists') ) def __init__(self, expression): self.expression = expression def __call__(self, target, engine): return self.translate(self.expression, target) def rewrite(self, node): builtin = self.builtins.get(node.id) if builtin is not None: return template( "get(name) if get(name) is not None else builtin", get=Builtin("get"), name=ast.Str(s=node.id), builtin=builtin, mode="eval" ) @property def transform(self): return NameLookupRewriteVisitor(self.rewrite) z3c.pt-2.2.3/src/z3c/pt/configure.zcml0000644000175000001440000000110611542662564020062 0ustar mborchusers00000000000000 z3c.pt-2.2.3/src/z3c/pt/namespaces.py0000644000175000001440000000571611436764405017715 0ustar mborchusers00000000000000import zope.component from zope.traversing.interfaces import IPathAdapter class AdapterNamespaces(object): """Simulate tales function namespaces with adapter lookup. When we are asked for a namespace, we return an object that actually computes an adapter when called: To demonstrate this, we need to register an adapter: >>> def adapter1(ob): ... return 1 >>> zope.component.getGlobalSiteManager().registerAdapter( ... adapter1, [zope.interface.Interface], IPathAdapter, 'a1') Now, with this adapter in place, we can try out the namespaces: >>> ob = object() >>> namespaces = AdapterNamespaces() >>> namespace = namespaces['a1'] >>> namespace(ob) 1 >>> namespace = namespaces['a2'] >>> namespace(ob) Traceback (most recent call last): ... KeyError: 'a2' """ def __init__(self): self.namespaces = {} def __getitem__(self, name): namespace = self.namespaces.get(name) if namespace is None: def namespace(object): try: return zope.component.getAdapter(object, IPathAdapter, name) except zope.component.ComponentLookupError: raise KeyError(name) self.namespaces[name] = namespace return namespace def registerFunctionNamespace(self, namespacename, namespacecallable): """Register a function namespace namespace - a string containing the name of the namespace to be registered namespacecallable - a callable object which takes the following parameter: context - the object on which the functions provided by this namespace will be called This callable should return an object which can be traversed to get the functions provided by the this namespace. example: class stringFuncs(object): def __init__(self,context): self.context = str(context) def upper(self): return self.context.upper() def lower(self): return self.context.lower() engine.registerFunctionNamespace('string',stringFuncs) """ self.namespaces[namespacename] = namespacecallable def getFunctionNamespace(self, namespacename): """ Returns the function namespace """ return self.namespaces[namespacename] try: # If zope.app.pagetemplates is available, use the adapter # registered with the main zope.app.pagetemplates engine so that # we don't need to re-register them. from zope.app.pagetemplates.engine import Engine function_namespaces = Engine.namespaces except (ImportError, AttributeError): function_namespaces = AdapterNamespaces() z3c.pt-2.2.3/src/z3c/pt/loader.py0000644000175000001440000000032611532725403017024 0ustar mborchusers00000000000000from z3c.pt.pagetemplate import PageTemplateFile from chameleon import loader class TemplateLoader(loader.TemplateLoader): def load_page(self, filename): return self.load(filename, PageTemplateFile) z3c.pt-2.2.3/src/z3c/pt/README.txt0000644000175000001440000003404311530421321016673 0ustar mborchusers00000000000000z3c.pt ====== This section demonstrates the high-level template classes. All page template classes in ``z3c.pt`` use path-expressions by default. Page templates -------------- >>> from z3c.pt.pagetemplate import PageTemplate >>> from z3c.pt.pagetemplate import PageTemplateFile The ``PageTemplate`` class is initialized with a string. >>> template = PageTemplate("""\ ...
... Hello World! ...
""") >>> print template()
Hello World!
The ``PageTemplateFile`` class is initialized with an absolute path to a template file on disk. >>> template_file = PageTemplateFile('tests/helloworld.pt') >>> print template_file()
Hello World!
>>> import os >>> template_file.filename.startswith(os.sep) True If a ``content_type`` is not informed and one is not present in the request, it will be set to 'text/html'. >>> class Response(object): ... def __init__(self): ... self.headers = {} ... self.getHeader = self.headers.get ... self.setHeader = self.headers.__setitem__ >>> class Request(object): ... def __init__(self): ... self.response = Response() >>> template_file = PageTemplateFile('tests/helloworld.pt') >>> request = Request() >>> print request.response.getHeader('Content-Type') None >>> template = template_file.bind(None, request=request) >>> print template()
Hello World!
>>> print request.response.getHeader('Content-Type') text/html If a ``content_type`` is present in the request, then we don't override it. >>> request = Request() >>> request.response.setHeader('Content-Type', 'text/xml') >>> print request.response.getHeader('Content-Type') text/xml >>> template = template_file.bind(None, request=request) >>> print template()
Hello World!
>>> print request.response.getHeader('Content-Type') text/xml A ``content_type`` can be also set at instantiation time, and it will be respected. >>> template_file = PageTemplateFile('tests/helloworld.pt', ... content_type='application/rdf+xml') >>> request = Request() >>> print request.response.getHeader('Content-Type') None >>> template = template_file.bind(None, request=request) >>> print template()
Hello World!
>>> print request.response.getHeader('Content-Type') application/rdf+xml Both may be used as class attributes (properties). >>> class MyClass(object): ... template = PageTemplate("""\ ...
... Hello World! ...
""") ... ... template_file = PageTemplateFile('tests/helloworld.pt') >>> instance = MyClass() >>> print instance.template()
Hello World!
>>> print instance.template_file()
Hello World!
View page templates ------------------- >>> from z3c.pt.pagetemplate import ViewPageTemplate >>> from z3c.pt.pagetemplate import ViewPageTemplateFile >>> class View(object): ... request = u'request' ... context = u'context' ... ... def __repr__(self): ... return 'view' >>> view = View() As before, we can initialize view page templates with a string (here incidentally loaded from disk). >>> from z3c.pt import tests >>> path = tests.__path__[0] >>> template = ViewPageTemplate( ... open(path + '/view.pt').read()) To render the template in the context of a view, we bind the template passing the view as an argument (view page templates derive from the ``property``-class and are usually defined as an attribute on a view class). >>> print template.bind(view)(test=u'test')
view context request test test
The exercise is similar for the file-based variant. >>> template = ViewPageTemplateFile('tests/view.pt') >>> print template.bind(view)(test=u'test')
view context request test test
For compatibility reasons, view templates may be called with an alternative context and request. >>> print template(view, u"alt_context", "alt_request", test=u'test')
view alt_context alt_request test test
Non-keyword arguments --------------------- These are passed in as ``options/args``, when using the ``__call__`` method. >>> print PageTemplate("""\ ...
...
... ...
...
""").__call__(1, 2, 3)
1
2
3
Global 'path' Function ---------------------- Just like ``zope.pagetemplate``, it is possible to use a globally defined ``path()`` function in a ``python:`` expression in ``z3c.pt``: >>> template = PageTemplate("""\ ...
... ... ...
""") >>> print template(test='test')
test test
Global 'exists' Function ------------------------ The same applies to the ``exists()`` function: >>> template = PageTemplate("""\ ...
... ...
""") >>> print template(test='test')
Yes
'default' and path expressions ------------------------------ Another feature from standard ZPT: using 'default' means whatever the the literal HTML contains will be output if the condition is not met. This works for attributes: >>> template = PageTemplate("""\ ...
... i'm blue ...
""") >>> print template()
i'm blue
And also for contents: >>> template = PageTemplate("""\ ...
... default content ...
""") >>> print template()
default content
'exists'-type expression ------------------------ Using 'exists()' function on non-global name and global name: >>> template = PageTemplate("""\ ...
... do I exist? ... do I exist? ...
""") >>> print template()
No No
Using 'exists:' expression on non-global name and global name >>> template = PageTemplate("""\ ...
... do I exist? ... do I exist? ...
""") >>> print template()
No No
Using 'exists:' in conjunction with a negation: >>> print PageTemplate("""\ ...
... I don't exist? ...
""")()
I don't exist?
path expression with dictionaries --------------------------------- Path expressions give preference to dictionary items instead of dictionary attributes. >>> print PageTemplate("""\ ...
... ZZZ ...
""")()
XXX
Variable from one tag never leak into another --------------------------------------------- >>> body = """\ ...
...
... ...
...
... ...
...
... ...
...
""" >>> print PageTemplate(body)()
'Hey'
'Hello'
'Hey'
TALES Function Namespaces ------------------------- As described on http://wiki.zope.org/zope3/talesns.html, it is possible to implement custom TALES Namespace Adapters. We also support low-level TALES Function Namespaces (which the TALES Namespace Adapters build upon). >>> import datetime >>> import zope.interface >>> import zope.component >>> from zope.traversing.interfaces import ITraversable >>> from zope.traversing.interfaces import IPathAdapter >>> from zope.tales.interfaces import ITALESFunctionNamespace >>> from z3c.pt.namespaces import function_namespaces >>> class ns1(object): ... zope.interface.implements(ITALESFunctionNamespace) ... def __init__(self, context): ... self.context = context ... def parent(self): ... return self.context.parent >>> function_namespaces.registerFunctionNamespace('ns1', ns1) >>> class ns2(object): ... def __init__(self, context): ... self.context = context ... def upper(self): ... return self.context.upper() >>> zope.component.getGlobalSiteManager().registerAdapter( ... ns2, [zope.interface.Interface], IPathAdapter, 'ns2') >>> class ns3(object): ... def __init__(self, context): ... self.context = context ... def fullDateTime(self): ... return self.context.strftime('%Y-%m-%d %H:%M:%S') >>> zope.component.getGlobalSiteManager().registerAdapter( ... ns3, [zope.interface.Interface], IPathAdapter, 'ns3') A really corner-ish case from a legacy application: the TALES Namespace Adapter doesn't have a callable function but traverses the remaining path instead:: >>> from zope.traversing.interfaces import TraversalError >>> class ns4(object): ... zope.interface.implements(ITraversable) ... ... def __init__(self, context): ... self.context = context ... ... def traverse(self, name, furtherPath): ... if name == 'page': ... if len(furtherPath) == 1: ... pagetype = furtherPath.pop() ... elif not furtherPath: ... pagetype = 'default' ... else: ... raise TraversalError("Max 1 path segment after ns4:page") ... return self._page(pagetype) ... if len(furtherPath) == 1: ... name = '%s/%s' % (name, furtherPath.pop()) ... return 'traversed: ' + name ... ... def _page(self, pagetype): ... return 'called page: ' + pagetype >>> zope.component.getGlobalSiteManager().registerAdapter( ... ns4, [zope.interface.Interface], IPathAdapter, 'ns4') >>> class ns5(object): ... zope.interface.implements(ITraversable) ... ... def __init__(self, context): ... self.context = context ... ... def traverse(self, name, furtherPath): ... name = '/'.join([name] + furtherPath[::-1]) ... del furtherPath[:] ... return 'traversed: ' + name >>> zope.component.getGlobalSiteManager().registerAdapter( ... ns5, [zope.interface.Interface], IPathAdapter, 'ns5') >>> class Ob(object): ... def __init__(self, title, date, parent=None, child=None): ... self.title = title ... self.date = date ... self.parent = parent ... self.child = child >>> child = Ob('child', datetime.datetime(2008, 12, 30, 13, 48, 0, 0)) >>> father = Ob('father', datetime.datetime(1978, 12, 30, 13, 48, 0, 0)) >>> grandpa = Ob('grandpa', datetime.datetime(1948, 12, 30, 13, 48, 0, 0)) >>> child.parent = father >>> father.child = child >>> father.parent = grandpa >>> grandpa.child = father >>> class View(object): ... request = u'request' ... context = father ... ... def __repr__(self): ... return 'view' >>> view = View() >>> template = ViewPageTemplateFile('tests/function_namespaces.pt') >>> print template.bind(view)()
GRANDPA 2008-12-30 13:48:00 traversed: link:main called page: default called page: another traversed: zope.Public traversed: text-to-html traversed: page/yet/even/another
z3c.pt-2.2.3/src/z3c/pt/tests/0000755000175000001440000000000011762105444016347 5ustar mborchusers00000000000000z3c.pt-2.2.3/src/z3c/pt/tests/provider.pt0000644000175000001440000000026511634064223020546 0ustar mborchusers00000000000000
z3c.pt-2.2.3/src/z3c/pt/tests/path.pt0000644000175000001440000000052511620672012017643 0ustar mborchusers00000000000000
WYSWIWYG supported.
z3c.pt-2.2.3/src/z3c/pt/tests/test_templates.py0000644000175000001440000000717611702334616021770 0ustar mborchusers00000000000000import unittest import zope.component.testing import zope.configuration.xmlconfig class TestPageTemplateFile(unittest.TestCase): def setUp(self): import z3c.pt zope.component.testing.setUp(self) zope.configuration.xmlconfig.XMLConfig('configure.zcml', z3c.pt)() def tearDown(self): zope.component.testing.tearDown(self) def test_nocall(self): from z3c.pt.pagetemplate import PageTemplateFile template = PageTemplateFile("nocall.pt") def dont_call(): raise RuntimeError() result = template(callable=dont_call) self.failUnless(repr(dont_call) in result) def test_exists(self): from z3c.pt.pagetemplate import PageTemplateFile template = PageTemplateFile("exists.pt") def dont_call(): raise RuntimeError() result = template(callable=dont_call) self.failUnless('ok' in result) def test_false_attribute(self): from z3c.pt.pagetemplate import PageTemplateFile template = PageTemplateFile("false.pt") result = template() self.failUnless('False' in result) def test_boolean_attribute(self): from z3c.pt.pagetemplate import PageTemplateFile template = PageTemplateFile("boolean.pt") result = template() self.failIf('False' in result) self.failUnless('checked="checked"' in result) def test_path(self): from z3c.pt.pagetemplate import PageTemplateFile template = PageTemplateFile("path.pt") class Context(object): dummy_wysiwyg_support = True context = Context() template = template.__get__(context, Context) result = template(editor="dummy") self.failUnless("supported" in result) self.failUnless("some path" in result) def test_provider(self): from z3c.pt.pagetemplate import ViewPageTemplateFile class Context(object): pass class Request(object): response = None class View(object): __call__ = ViewPageTemplateFile("provider.pt") from zope.interface import Interface from zope.schema import Field from zope.interface import implements from zope.interface import directlyProvides from zope.contentprovider.interfaces import ITALNamespaceData class ITestProvider(Interface): context = Field(u"Provider context.") directlyProvides(ITestProvider, ITALNamespaceData) assert ITALNamespaceData.providedBy(ITestProvider) class Provider(object): implements(ITestProvider) def __init__(self, *args): data.extend(list(args)) def update(self): data.extend("updated") def render(self): return """""" % ( data, self.__dict__) view = View() data = [] from zope.interface import implementedBy from zope.component import provideAdapter from zope.contentprovider.interfaces import IContentProvider provideAdapter( Provider, ( implementedBy(Context), implementedBy(Request), implementedBy(View) ), IContentProvider, name="content" ) context = Context() request = Request() result = view(context=context, request=request) self.failUnless(repr(data) in result) self.failUnless(repr({'context': context}) in result) def test_suite(): import sys return unittest.findTestCases(sys.modules[__name__]) z3c.pt-2.2.3/src/z3c/pt/tests/false.pt0000644000175000001440000000013411624457665020020 0ustar mborchusers00000000000000
z3c.pt-2.2.3/src/z3c/pt/tests/test_doctests.py0000644000175000001440000000163411542632276021620 0ustar mborchusers00000000000000import doctest import unittest OPTIONFLAGS = (doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE) import zope.component.testing import zope.configuration.xmlconfig import z3c.pt def setUp(suite): zope.component.testing.setUp(suite) zope.configuration.xmlconfig.XMLConfig('configure.zcml', z3c.pt)() def test_suite(): filesuites = 'README.txt', testsuites = 'z3c.pt.expressions', 'z3c.pt.namespaces' return unittest.TestSuite( [doctest.DocFileSuite( filesuite, optionflags=OPTIONFLAGS, setUp=setUp, tearDown=zope.component.testing.tearDown, package="z3c.pt") for filesuite in filesuites] + \ [doctest.DocTestSuite( testsuite, optionflags=OPTIONFLAGS, setUp=setUp, tearDown=zope.component.testing.tearDown) \ for testsuite in testsuites] ) if __name__ == '__main__': unittest.main(defaultTest='test_suite') z3c.pt-2.2.3/src/z3c/pt/tests/view.css0000644000175000001440000000005511436764404020040 0ustar mborchusers00000000000000#region { background: ${options/color}; }z3c.pt-2.2.3/src/z3c/pt/tests/function_namespaces.pt0000644000175000001440000000112711436764404022746 0ustar mborchusers00000000000000
z3c.pt-2.2.3/src/z3c/pt/tests/exists.pt0000644000175000001440000000006611542662327020241 0ustar mborchusers00000000000000
ok
z3c.pt-2.2.3/src/z3c/pt/tests/nocall.pt0000644000175000001440000000007011542662322020160 0ustar mborchusers00000000000000
z3c.pt-2.2.3/src/z3c/pt/tests/boolean.pt0000644000175000001440000000017511624457320020336 0ustar mborchusers00000000000000
z3c.pt-2.2.3/src/z3c/pt/tests/helloworld.pt0000644000175000001440000000010111436764404021064 0ustar mborchusers00000000000000
Hello World!
z3c.pt-2.2.3/src/z3c/pt/tests/view.pt0000644000175000001440000000050211436764404017670 0ustar mborchusers00000000000000
z3c.pt-2.2.3/src/z3c/pt/tests/__init__.py0000644000175000001440000000000011436764404020453 0ustar mborchusers00000000000000z3c.pt-2.2.3/src/z3c/pt/tests/test_loader.py0000644000175000001440000000307411542632323021227 0ustar mborchusers00000000000000import unittest class LoadTests: def _makeOne(self, search_path=None, **kwargs): klass = self._getTargetClass() return klass(search_path, **kwargs) def _getTargetClass(self): from z3c.pt.loader import TemplateLoader return TemplateLoader def test_load_relative(self): import os here = os.path.dirname(__file__) loader = self._makeOne(search_path = [here]) result = self._load(loader, 'view.pt') self.assertEqual(result.filename, os.path.join(here, 'view.pt')) def test_consecutive_loads(self): import os here = os.path.dirname(__file__) loader = self._makeOne(search_path = [here]) self.assertTrue( self._load(loader, 'view.pt') is self._load(loader, 'view.pt')) def test_load_relative_badpath_in_searchpath(self): import os here = os.path.dirname(__file__) loader = self._makeOne(search_path = [os.path.join(here, 'none'), here]) result = self._load(loader, 'view.pt') self.assertEqual(result.filename, os.path.join(here, 'view.pt')) def test_load_abs(self): import os here = os.path.dirname(__file__) loader = self._makeOne() abs = os.path.join(here, 'view.pt') result = self._load(loader, abs) self.assertEqual(result.filename, abs) class LoadPageTests(unittest.TestCase, LoadTests): def _load(self, loader, filename): return loader.load_page(filename) def test_suite(): import sys return unittest.findTestCases(sys.modules[__name__]) z3c.pt-2.2.3/src/z3c/pt/pagetemplate.py0000644000175000001440000002106611762105032020225 0ustar mborchusers00000000000000import os import sys from zope import i18n from zope.security.proxy import ProxyFactory from chameleon.i18n import fast_translate from chameleon.zpt import template from chameleon.tales import StringExpr from chameleon.tales import NotExpr from chameleon.compiler import ExpressionEvaluator from z3c.pt import expressions try: from Missing import MV MV # pyflakes except ImportError: MV = object() _marker = object() BOOLEAN_HTML_ATTRS = frozenset([ # List of Boolean attributes in HTML that should be rendered in # minimized form (e.g. rather than ) # From http://www.w3.org/TR/xhtml1/#guidelines (C.10) # TODO: The problem with this is that this is not valid XML and # can't be parsed back! "compact", "nowrap", "ismap", "declare", "noshade", "checked", "disabled", "readonly", "multiple", "selected", "noresize", "defer" ]) class OpaqueDict(dict): def __new__(cls, dictionary): inst = dict.__new__(cls) inst.dictionary = dictionary return inst @property def __getitem__(self): return self.dictionary.__getitem__ @property def __len__(self): return self.dictionary.__len__ def __repr__(self): return "{...} (%d entries)" % len(self) sys_modules = ProxyFactory(OpaqueDict(sys.modules)) class DummyRegistry(object): """This class is for B/W with Chameleon 1.x API.""" @staticmethod def purge(): pass class BaseTemplate(template.PageTemplate): content_type = None version = 2 registry = DummyRegistry() expression_types = { 'python': expressions.PythonExpr, 'string': StringExpr, 'not': NotExpr, 'exists': expressions.ExistsExpr, 'path': expressions.PathExpr, 'provider': expressions.ProviderExpr, 'nocall': expressions.NocallExpr, } default_expression = "path" literal_false = True strict = False trim_attribute_space = True @property def boolean_attributes(self): if self.content_type == 'text/xml': return set() return BOOLEAN_HTML_ATTRS @property def builtins(self): builtins = { 'nothing': None, 'modules': sys_modules, } tales = ExpressionEvaluator(self.engine, builtins) builtins['tales'] = tales return builtins def bind(self, ob, request=None): def render(request=request, **kwargs): context = self._pt_get_context(ob, request, kwargs) return self.render(**context) return BoundPageTemplate(self, render) def render(self, target_language=None, **context): # We always include a ``request`` variable; it is (currently) # depended on in various expression types and must be defined request = context.setdefault('request', None) if target_language is None: try: target_language = i18n.negotiate(request) except: target_language = None context['target_language'] = target_language # bind translation-method to request def translate( msgid, domain=None, mapping=None, target_language=None, default=None, context=None): if msgid is MV: # Special case handling of Zope2's Missing.MV # (Missing.Value) used by the ZCatalog but is # unhashable return return fast_translate( msgid, domain, mapping, request, target_language, default) context["translate"] = translate if request is not None and not isinstance(request, basestring): content_type = self.content_type or 'text/html' response = request.response if response and not response.getHeader("Content-Type"): response.setHeader( "Content-Type", content_type) base_renderer = super(BaseTemplate, self).render return base_renderer(**context) def __call__(self, *args, **kwargs): bound_pt = self.bind(self) return bound_pt(*args, **kwargs) def _pt_get_context(self, instance, request, kwargs): return dict( context=instance, here=instance, options=kwargs, request=request, template=self, ) class BaseTemplateFile(BaseTemplate, template.PageTemplateFile): """If ``filename`` is a relative path, the module path of the class where the instance is used to get an absolute path.""" cache = {} def __init__(self, filename, path=None, content_type=None, **kwargs): if path is not None: filename = os.path.join(path, filename) if not os.path.isabs(filename): for depth in (1, 2): frame = sys._getframe(depth) package_name = frame.f_globals.get('__name__', None) if package_name is not None and \ package_name != self.__module__: module = sys.modules[package_name] try: path = module.__path__[0] except AttributeError: path = module.__file__ path = path[:path.rfind(os.sep)] break else: package_path = frame.f_globals.get('__file__', None) if package_path is not None: path = os.path.dirname(package_path) break if path is not None: filename = os.path.join(path, filename) template.PageTemplateFile.__init__( self, filename, **kwargs) # Set content-type last, so that we can override whatever was # magically sniffed from the source template. self.content_type = content_type class PageTemplate(BaseTemplate): """Page Templates using TAL, TALES, and METAL. This class is suitable for standalone use or class property. Keyword-arguments are passed into the template as-is. Initialize with a template string.""" version = 1 def __get__(self, instance, type): if instance is not None: return self.bind(instance) return self class PageTemplateFile(BaseTemplateFile, PageTemplate): """Page Templates using TAL, TALES, and METAL. This class is suitable for standalone use or class property. Keyword-arguments are passed into the template as-is. Initialize with a filename.""" cache = {} class ViewPageTemplate(PageTemplate): """Template class suitable for use with a Zope browser view; the variables ``view``, ``context`` and ``request`` variables are brought in to the local scope of the template automatically, while keyword arguments are passed in through the ``options`` dictionary. Note that the default expression type for this class is 'path' (standard Zope traversal).""" def _pt_get_context(self, view, request, kwargs): context = kwargs.get('context') if context is None: context = view.context request = request or kwargs.get('request') or view.request return dict( view=view, context=context, request=request, options=kwargs, template=self, ) def __call__(self, _ob=None, context=None, request=None, **kwargs): kwargs.setdefault('context', context) kwargs.setdefault('request', request) bound_pt = self.bind(_ob) return bound_pt(**kwargs) class ViewPageTemplateFile(ViewPageTemplate, PageTemplateFile): """If ``filename`` is a relative path, the module path of the class where the instance is used to get an absolute path.""" cache = {} class BoundPageTemplate(object): """When a page template class is used as a property, it's bound to the class instance on access, which is implemented using this helper class.""" def __init__(self, pt, render): object.__setattr__(self, 'im_self', pt) object.__setattr__(self, 'im_func', render) macros = property(lambda self: self.im_self.macros) filename = property(lambda self: self.im_self.filename) def __call__(self, *args, **kw): kw.setdefault('args', args) return self.im_func(**kw) def __setattr__(self, name, v): raise AttributeError("Can't set attribute", name) def __repr__(self): return "<%s.Bound%s %r>" % ( type(self.im_self).__module__, type(self.im_self).__name__, self.filename) z3c.pt-2.2.3/src/z3c/pt/__init__.py0000644000175000001440000000036411436764405017327 0ustar mborchusers00000000000000# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) z3c.pt-2.2.3/src/z3c/__init__.py0000644000175000001440000000036411436764405016704 0ustar mborchusers00000000000000# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) z3c.pt-2.2.3/COPYRIGHT.txt0000644000175000001440000000004011436764405015405 0ustar mborchusers00000000000000Zope Foundation and Contributorsz3c.pt-2.2.3/README.txt0000644000175000001440000000043411436764405015001 0ustar mborchusers00000000000000Overview ======== This is a fast implementation of the ZPT template engine for Zope 3 which uses Chameleon to compile templates to byte-code. The package provides application support equivalent to ``zope.app.pagetemplate``. For usage, see the README.txt file inside the package. z3c.pt-2.2.3/AUTHOR.txt0000644000175000001440000000004011436764405015037 0ustar mborchusers00000000000000Malthe Borch z3c.pt-2.2.3/bootstrap.py0000644000175000001440000000733011530326370015662 0ustar mborchusers00000000000000############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs) z3c.pt-2.2.3/setup.py0000644000175000001440000000210711762105376015012 0ustar mborchusers00000000000000from setuptools import setup, find_packages version = '2.2.3' install_requires = [ 'setuptools', 'zope.interface', 'zope.component', 'zope.i18n >= 3.5', 'zope.traversing', 'zope.contentprovider', 'Chameleon >= 2.4', ] tests_require = [ 'zope.testing', ] setup(name='z3c.pt', version=version, description="Fast ZPT engine.", long_description=open("README.txt").read() + open("CHANGES.txt").read(), classifiers=[ "Programming Language :: Python", "Topic :: Text Processing :: Markup :: HTML", "Topic :: Text Processing :: Markup :: XML", ], keywords='', author='Malthe Borch and the Zope Community', author_email='zope-dev@zope.org', url='', license='ZPL', namespace_packages=['z3c'], packages = find_packages('src'), package_dir = {'':'src'}, include_package_data=True, zip_safe=False, install_requires=install_requires, extras_require=dict( test=tests_require, ), tests_require=tests_require, )