[Checkins] SVN: Sandbox/Chameleon/ Removed template language implementation code.
Malthe Borch
mborch at gmail.com
Mon Sep 15 17:10:52 EDT 2008
Log message for revision 91165:
Removed template language implementation code.
Changed:
U Sandbox/Chameleon/CHANGES.txt
U Sandbox/Chameleon/README.txt
D Sandbox/Chameleon/TODO.txt
D Sandbox/Chameleon/benchmark/
U Sandbox/Chameleon/buildout.cfg
U Sandbox/Chameleon/setup.py
A Sandbox/Chameleon/src/chameleon/
A Sandbox/Chameleon/src/chameleon/core/
U Sandbox/Chameleon/src/chameleon/core/__init__.py
U Sandbox/Chameleon/src/chameleon/core/clauses.py
U Sandbox/Chameleon/src/chameleon/core/codegen.txt
U Sandbox/Chameleon/src/chameleon/core/config.py
D Sandbox/Chameleon/src/chameleon/core/configure.zcml
U Sandbox/Chameleon/src/chameleon/core/expressions.py
D Sandbox/Chameleon/src/chameleon/core/genshi.py
D Sandbox/Chameleon/src/chameleon/core/genshi.txt
D Sandbox/Chameleon/src/chameleon/core/i18n.txt
U Sandbox/Chameleon/src/chameleon/core/loader.py
D Sandbox/Chameleon/src/chameleon/core/pagetemplate.py
U Sandbox/Chameleon/src/chameleon/core/template.py
U Sandbox/Chameleon/src/chameleon/core/template.txt
U Sandbox/Chameleon/src/chameleon/core/testing.py
U Sandbox/Chameleon/src/chameleon/core/tests/test_doctests.py
U Sandbox/Chameleon/src/chameleon/core/tests/test_edgecases.py
U Sandbox/Chameleon/src/chameleon/core/tests/test_loader.py
D Sandbox/Chameleon/src/chameleon/core/tests/view.css
D Sandbox/Chameleon/src/chameleon/core/tests/view.pt
D Sandbox/Chameleon/src/chameleon/core/tests/xinclude1.pt
D Sandbox/Chameleon/src/chameleon/core/tests/xinclude2.pt
D Sandbox/Chameleon/src/chameleon/core/tests/xinclude3.pt
D Sandbox/Chameleon/src/chameleon/core/tests/xinclude4.pt
D Sandbox/Chameleon/src/chameleon/core/texttemplate.py
U Sandbox/Chameleon/src/chameleon/core/translation.txt
U Sandbox/Chameleon/src/chameleon/core/utils.py
D Sandbox/Chameleon/src/chameleon/core/zpt.py
D Sandbox/Chameleon/src/chameleon/core/zpt.txt
D Sandbox/Chameleon/src/chameleon/pt/
D Sandbox/Chameleon/src/z3c/
-=-
Modified: Sandbox/Chameleon/CHANGES.txt
===================================================================
--- Sandbox/Chameleon/CHANGES.txt 2008-09-15 20:35:31 UTC (rev 91164)
+++ Sandbox/Chameleon/CHANGES.txt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,9 +1,13 @@
Changelog
----------
+=========
Version 1.0dev
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ Package changes
+
+- Split out compiler to separate egg. [malthe]
+
Backwards incompatibilities
- Moved contents of ``z3c.pt.macro`` module into
Modified: Sandbox/Chameleon/README.txt
===================================================================
--- Sandbox/Chameleon/README.txt 2008-09-15 20:35:31 UTC (rev 91164)
+++ Sandbox/Chameleon/README.txt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,78 +1,18 @@
Overview
--------
-The z3c.pt package provides a fast template engine that supports the
-following dialects of the attribute template language:
+Chameleon is a generic byte-code compiler for attribute template
+languages; it supports macros, includes, interpolation and
+internationalization.
-* Zope TAL
-* Zope METAL
-* Zope i18n
-* Genshi
-
-Non-structural documents are supported through Genshi's variable
-interpolation syntax which is also available for XML templates.
-
-Casual benchmarks pegs it 16x more performant than the reference
-implementations for Zope TAL and Genshi.
-
-In a nutshell:
-
-* Templates are serialized and compiled into Python bytecode
-* Pluggable expression implementation
-
-
-Usage
------
-
-See README.txt inside package for general usage; to register the
-default expression types, load the package component configuration
-file (configure.zcml).
-
-
-Compiler notes
---------------
-
-The compiler is largely compatible with the targeted dialects. The TAL
-implementation is based on the 1.4 language specification* while the
-Genshi implementation is based on the documents for the 0.5 release**.
-
-Some notable changes:
-
-1. Tuple unpacking is allowed when defining variables:
-
- tal:define="(a, b, c) [1, 2, 3]"
-
-2. Generators are allowed in tal:repeat statements. Note that the
- repeat variable is not available in this case.
-
- tal:repeat="i <some generator>"
-
-3. Attribute-access to dictionary entries is allowed in
- Python-expressions, e.g.
-
- dictionary.key
-
- can be used instead of ``dictionary['key']``.
-
-4. Default expression type can be set using ``tal:default-expression``.
- This is an alternative to providing the expression type before each
- expression.
-
-5. The XPath select function provided to py:match-elements uses lxml
- and requires the use of the default namespace prefix "xmlns".
-
-.. _TAL: http://wiki.zope.org/ZPT/TALSpecification14
-.. _Genshi: http://genshi.edgewall.org/wiki/Documentation/xml-templates.html
-
-
Development
-----------
If you want to use the code directly from trunk (recommended only for
-development and testing usage), provide ``z3c.pt==dev`` as your
+development and testing usage), provide ``Chameleon==dev`` as your
dependency.
-svn://svn.zope.org/repos/main/z3c.pt/trunk#egg=z3c.pt-dev
+svn://svn.zope.org/repos/main/Sandbox/Chameleon#egg=Chameleon-dev
-Want to contribute? Join #zope3-dev on Freenode IRC.
+Want to contribute? Join #repoze on Freenode IRC.
Deleted: Sandbox/Chameleon/TODO.txt
===================================================================
--- Sandbox/Chameleon/TODO.txt 2008-09-15 20:35:31 UTC (rev 91164)
+++ Sandbox/Chameleon/TODO.txt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,4 +0,0 @@
-- Make e.g. <tal:block tal:foo /> and <metal:foo metal:define-macro/> etc.
- work
-
--
Modified: Sandbox/Chameleon/buildout.cfg
===================================================================
--- Sandbox/Chameleon/buildout.cfg 2008-09-15 20:35:31 UTC (rev 91164)
+++ Sandbox/Chameleon/buildout.cfg 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,12 +1,8 @@
[buildout]
-develop =
- .
- benchmark
-
+develop = .
parts =
test
test-nolxml
- benchmark
py
py-nolxml
@@ -14,41 +10,29 @@
recipe = zc.recipe.testrunner
environment = test-environment
eggs =
- z3c.pt [lxml]
+ Chameleon [lxml]
[test-nolxml]
recipe = zc.recipe.testrunner
environment = test-environment
eggs =
- z3c.pt
+ Chameleon
[test-environment]
Z3C_PT_DEBUG = False
-[benchmark]
-recipe = zc.recipe.testrunner
-environment = benchmark-environment
-eggs =
- z3c.pt [lxml]
- benchmark
-
-[benchmark-environment]
-Z3C_PT_DEBUG = False
-zope_i18n_allowed_languages = en, da, de
-
[py]
recipe = zc.recipe.egg
eggs =
- z3c.pt [lxml]
- benchmark
+ Chameleon [lxml]
Sphinx
interpreter = py
-environment = benchmark-environment
+environment = test-environment
scripts = sphinx-build
[py-nolxml]
recipe = zc.recipe.egg
eggs =
- z3c.pt
+ Chameleon
interpreter = py-nolxml
-environment = benchmark-environment
+environment = test-environment
Modified: Sandbox/Chameleon/setup.py
===================================================================
--- Sandbox/Chameleon/setup.py 2008-09-15 20:35:31 UTC (rev 91164)
+++ Sandbox/Chameleon/setup.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -7,18 +7,14 @@
'zope.interface',
'zope.component',
'zope.i18n >= 3.5',
- 'zope.traversing',
- 'zope.contentprovider',
]
if sys.version_info[:3] < (2,5,0):
install_requires.append('elementtree')
-setup(name='z3c.pt',
+setup(name='Chameleon',
version=version,
- description="Python template compiler which supports the Genshi and "
- "ZPT template languages including macro extensions and "
- "internationalization.",
+ description="Attribute language template compiler",
long_description=open("README.txt").read() + open("CHANGES.txt").read(),
classifiers=[
"Programming Language :: Python",
@@ -30,8 +26,8 @@
author='Malthe Borch and the Zope Community',
author_email='zope-dev at zope.org',
url='',
- license='ZPL',
- namespace_packages=['z3c'],
+ license='BSD',
+ namespace_packages=['chameleon'],
packages = find_packages('src'),
package_dir = {'':'src'},
include_package_data=True,
Copied: Sandbox/Chameleon/src/chameleon (from rev 91162, Sandbox/Chameleon/src/z3c)
Copied: Sandbox/Chameleon/src/chameleon/core (from rev 91162, Sandbox/Chameleon/src/z3c/pt)
Modified: Sandbox/Chameleon/src/chameleon/core/__init__.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/__init__.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/__init__.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,6 +1 @@
-# 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__)
+#
Modified: Sandbox/Chameleon/src/chameleon/core/clauses.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/clauses.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/clauses.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,11 +1,11 @@
-from z3c.pt import types
-from z3c.pt import config
-from z3c.pt import etree
-from z3c.pt import utils
+from chameleon.core import types
+from chameleon.core import config
+from chameleon.core import etree
+from chameleon.core import utils
class Assign(object):
"""
- >>> from z3c.pt import testing
+ >>> from chameleon.core import testing
We'll define some values for use in the tests.
@@ -138,7 +138,7 @@
class Define(object):
"""
- >>> from z3c.pt import testing
+ >>> from chameleon.core import testing
Variable scope:
@@ -303,7 +303,7 @@
class Condition(object):
"""
- >>> from z3c.pt import testing
+ >>> from chameleon.core import testing
Unlimited scope:
@@ -425,7 +425,7 @@
class Tag(object):
"""
- >>> from z3c.pt import testing
+ >>> from chameleon.core import testing
Dynamic attribute:
@@ -607,11 +607,11 @@
class Repeat(object):
"""
- >>> from z3c.pt import testing
+ >>> from chameleon.core import testing
We need to set up the repeat object.
- >>> from z3c.pt import utils
+ >>> from chameleon.core import utils
>>> repeat = utils.repeatdict()
Simple repeat loop and repeat data structure:
@@ -721,7 +721,7 @@
class Write(object):
"""
- >>> from z3c.pt import testing
+ >>> from chameleon.core import testing
Basic write:
@@ -824,7 +824,7 @@
class UnicodeWrite(Write):
"""
- >>> from z3c.pt import testing
+ >>> from chameleon.core import testing
Basic write:
@@ -873,7 +873,7 @@
class Out(object):
"""
- >>> from z3c.pt import testing
+ >>> from chameleon.core import testing
>>> _out, _write, stream = testing.setup_stream()
>>> out = Out('Hello World!')
@@ -899,7 +899,7 @@
class Method(object):
"""
- >>> from z3c.pt import testing
+ >>> from chameleon.core import testing
>>> _out, _write, stream = testing.setup_stream()
>>> _scope = {}
Modified: Sandbox/Chameleon/src/chameleon/core/codegen.txt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/codegen.txt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/codegen.txt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -10,7 +10,7 @@
The ``Suite`` class compiles a source code suite and makes a code
object available.
- >>> from z3c.pt.codegen import Suite
+ >>> from chameleon.core.codegen import Suite
>>> suite = Suite("""\
... print 'Hello World!'
... """)
Modified: Sandbox/Chameleon/src/chameleon/core/config.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/config.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/config.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -4,12 +4,12 @@
TRUEVALS = ('y', 'yes', 't', 'true', 'on', '1')
# in debug-mode, templates on disk are reloaded if they're modified
-DEBUG_MODE_KEY = 'Z3C_PT_DEBUG'
+DEBUG_MODE_KEY = 'CHAMELEON_DEBUG'
DEBUG_MODE = os.environ.get(DEBUG_MODE_KEY, 'false')
DEBUG_MODE = DEBUG_MODE.lower() in TRUEVALS
# disable disk-cache to prevent the compiler from caching on disk
-DISK_CACHE_KEY = 'Z3C_PT_CACHE'
+DISK_CACHE_KEY = 'CHAMELEON_CACHE'
DISK_CACHE = os.environ.get(DISK_CACHE_KEY, 'true')
DISK_CACHE = DISK_CACHE.lower() in TRUEVALS
CACHE_EXTENSION = "cache"
@@ -20,7 +20,7 @@
# use the disable-i18n flag to disable the translation machinery; this
# will speed up templates that use internationalization
-DISABLE_I18N_KEY = 'Z3C_PT_DISABLE_I18N'
+DISABLE_I18N_KEY = 'CHAMELEON_DISABLE_I18N'
DISABLE_I18N = os.environ.get(DISABLE_I18N_KEY, 'false')
DISABLE_I18N = DISABLE_I18N.lower() in TRUEVALS
Deleted: Sandbox/Chameleon/src/chameleon/core/configure.zcml
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/configure.zcml 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/configure.zcml 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,35 +0,0 @@
-<configure package="z3c.pt"
- xmlns="http://namespaces.zope.org/zope"
- xmlns:zcml="http://namespaces.zope.org/zcml">
-
- <include package="zope.component" file="meta.zcml" />
-
- <utility
- name="python"
- component=".expressions.python_translation" />
-
- <utility
- name="path"
- component=".expressions.path_translation" />
-
- <utility
- name="provider"
- component=".expressions.provider_translation" />
-
- <adapter
- name="string"
- factory=".expressions.StringTranslation" />
-
- <configure zcml:condition="installed zope.app.component">
-
- <include package="zope.app.component" file="meta.zcml" />
- <include package="zope.app.security" file="meta.zcml" />
-
- <class class=".utils.repeatitem">
- <allow interface=".interfaces.ITALESIterator" />
- </class>
-
- </configure>
-
-</configure>
-
Modified: Sandbox/Chameleon/src/chameleon/core/expressions.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/expressions.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/expressions.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,10 +1,6 @@
import zope.interface
import zope.component
-from zope.traversing.adapters import traversePathElement
-from zope.contentprovider.interfaces import IContentProvider
-from zope.contentprovider.interfaces import ContentProviderLookupError
-
import parser
import re
@@ -647,136 +643,3 @@
"Semi-colons in string-expressions must be escaped.")
return string.replace(';;', ';')
-
-class ZopeTraverser(object):
- def __init__(self, proxify=utils.identity):
- self.proxify = proxify
-
- def __call__(self, base, request, call, *path_items):
- """See ``zope.app.pagetemplate.engine``."""
-
- length = len(path_items)
- if length:
- i = 0
- while i < length:
- name = path_items[i]
- i += 1
- next = getattr(base, name, _marker)
- if next is not _marker:
- base = next
- continue
- else:
- # special-case dicts for performance reasons
- if isinstance(base, dict):
- base = base[name]
- else:
- base = traversePathElement(
- base, name, path_items[i:], request=request)
-
- if not isinstance(base, (basestring, tuple, list)):
- base = self.proxify(base)
-
- if call and getattr(base, '__call__', _marker) is not _marker:
- return base()
-
- return base
-
-class PathTranslation(ExpressionTranslation):
- path_regex = re.compile(
- r'^((nocall|not):\s*)*([A-Za-z_][A-Za-z0-9_]*)'+
- r'(/[A-Za-z_ at -][A-Za-z0-9_ at -\\.]*)*$')
-
- path_traverse = ZopeTraverser()
-
- def validate(self, string):
- if not self.path_regex.match(string.strip()):
- raise SyntaxError("Not a valid path-expression.")
-
- def translate(self, string):
- """
- >>> translate = PathTranslation().translate
- >>> translate("a/b")
- value("_path(a, request, True, 'b')")
-
- >>> translate("context/@@view")
- value("_path(context, request, True, '@@view')")
-
- >>> translate("nocall: context/@@view")
- value("_path(context, request, False, '@@view')")
-
- >>> translate("not: context/@@view")
- value("not(_path(context, request, True, '@@view'))")
-
- """
-
- nocall = False
- negate = False
-
- while string:
- m = self.re_pragma.match(string)
- if m is None:
- break
-
- string = string[m.end():]
- pragma = m.group('pragma').lower()
-
- if pragma == 'nocall':
- nocall = True
- elif pragma == 'not':
- negate = True
- else:
- raise ValueError("Invalid pragma: %s" % pragma)
-
- parts = string.strip().split('/')
-
- # map 'nothing' to 'None'
- parts = map(lambda part: part == 'nothing' and 'None' or part, parts)
-
- base = parts[0]
- components = [repr(part) for part in parts[1:]]
-
- if not components:
- components = ()
-
- value = types.value(
- '%s(%s, request, %s, %s)' % \
- (config.SYMBOLS.path, base, not nocall, ', '.join(components)))
-
- if negate:
- value = types.value('not(%s)' % value)
-
- value.symbol_mapping[config.SYMBOLS.path] = self.path_traverse
-
- return value
-
-path_translation = PathTranslation()
-
-def get_content_provider(context, request, view, name):
- 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)
-
- cp.update()
- return cp.render()
-
-class ProviderTranslation(object):
- zope.interface.implements(interfaces.IExpressionTranslation)
-
- provider_regex = re.compile(r'^[A-Za-z][A-Za-z0-9_-]*$')
- symbol = '_get_content_provider'
-
- def validate(self, string):
- if self.provider_regex.match(string) is None:
- raise SyntaxError(
- "%s is not a valid content provider name." % string)
-
- def translate(self, string):
- value = types.value("%s(context, request, view, '%s')" % \
- (self.symbol, string))
- value.symbol_mapping[self.symbol] = get_content_provider
- return value
-
-provider_translation = ProviderTranslation()
Deleted: Sandbox/Chameleon/src/chameleon/core/genshi.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/genshi.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/genshi.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,237 +0,0 @@
-import translation
-import expressions
-import utils
-import config
-import etree
-
-class GenshiElement(translation.Element, translation.VariableInterpolation):
- """Genshi element.
-
- Implements the Genshi subset of the attribute template language.
- """
-
- class node(translation.Node):
- @property
- def omit(self):
- if self.element.py_strip is not None:
- return self.element.py_strip or True
- if self.element.meta_omit is not None:
- return self.element.meta_omit or True
- if self.element.py_replace or self.element.meta_replace:
- return True
- if self.element.xi_href:
- return True
-
- @property
- def define(self):
- return self.element.py_with
-
- @property
- def condition(self):
- return self.element.py_if
-
- @property
- def repeat(self):
- return self.element.py_for
-
- @property
- def content(self):
- return self.element.py_content or self.element.py_replace or \
- self.element.meta_replace
-
- @property
- def skip(self):
- return bool(self.content)
-
- @property
- def dict_attributes(self):
- return self.element.py_attrs
-
- @property
- def dynamic_attributes(self):
- return self.element.meta_attributes
-
- @property
- def static_attributes(self):
- return utils.get_attributes_from_namespace(
- self.element, config.XHTML_NS)
-
- @property
- def macro(self):
- return self.element.py_def
-
- @property
- def cdata(self):
- return self.element.meta_cdata
-
- @property
- def include(self):
- return self.element.xi_href
-
- @property
- def format(self):
- return self.element.xi_parse
-
- node = property(node)
-
- def update(self):
- # Step 1: Convert py:choose, py:when, py:otherwise into
- # tal:define, tal:condition
- stream = self.stream
- choose_expression = self._pull_attribute(utils.py_attr('choose'))
- if choose_expression is not None:
- choose_variable = stream.save()
-
- if choose_expression:
- self._add_define(choose_variable, choose_expression)
-
- # select all elements that have the "py:when" controller,
- # unless a "py:choose" expression sits in-between
- variables = []
- for element in self.xpath(
- './*[@py:when]|.//*[not(@py:choose)]/*[@py:when]',
- namespaces={'py': config.PY_NS}):
-
- expression = element._pull_attribute(utils.py_attr('when'))
- variable = stream.save()
- variables.append(variable)
-
- # add definition to ancestor
- self._add_define(variable, expression)
-
- # add condition to element
- if choose_expression:
- expression = "python: %s == %s" % (
- choose_variable, variable)
- else:
- expression = "python: %s" % variable
-
- element.attrib[utils.py_attr('if')] = expression
-
- # process any "py:otherwise"-controllers
- for element in self.xpath(
- './*[@py:otherwise]|.//*[not(@py:choose)]/*[@py:otherwise]',
- namespaces={'py': config.PY_NS}):
- if choose_expression:
- expression = "python: %s not in %s" % (
- choose_variable, repr(tuple(variables)))
- else:
- expression = "python: not(%s)" % " or ".join(variables)
-
- element.attrib[utils.py_attr('if')] = expression
-
- # Step 2: Process "py:match" macros
- for element in self:
- if getattr(element, 'py_match', None) is None:
- continue
-
- nsmap = element.nsmap.copy()
-
- # default namespace is not allowed in XPath
- nsmap['xmlns'] = nsmap[None]
- del nsmap[None]
-
- # define macro
- name = stream.save()
- element.attrib[utils.py_attr('def')] = "%s(select)" % name
-
- matches = self.getroottree().getroot().xpath(
- element.py_match, namespaces=nsmap)
- for match in matches:
- # save reference to bound xpath-function
- select = stream.save()
- stream.selectors[select] = match.xpath
-
- # replace matched element with macro
- expression = "%s(%s)" % (name, select)
- match.attrib[utils.py_attr('replace')] = expression
-
- # save select-variable as element attribute
- match.attrib[utils.meta_attr('select')] = select
-
- # Step 3: Variable interpolation
- translation.VariableInterpolation.update(self)
-
- def _add_define(self, variable, expression):
- name = utils.py_attr('with')
- define = "%s=%s; " % (variable, expression)
-
- if name in self.attrib:
- self.attrib[name] += define
- else:
- self.attrib[name] = define
-
- def _pull_attribute(self, name, default=None):
- attrib = self.attrib
- if name in attrib:
- value = attrib[name]
- del attrib[name]
- return value
- return default
-
-class XHTMLElement(GenshiElement):
- """XHTML namespace element."""
-
- py_if = utils.attribute(
- utils.py_attr('if'), lambda p: p.expression)
- py_for = utils.attribute(
- utils.py_attr('for'), lambda p: p.definition)
- py_with = utils.attribute(utils.py_attr('with'),
- lambda p: expressions.python_translation.definitions)
- py_choose = utils.attribute(
- utils.py_attr('choose'), lambda p: p.expression)
- py_when = utils.attribute(
- utils.py_attr('when'), lambda p: p.expression)
- py_match = utils.attribute(
- utils.py_attr('match'))
- py_def = utils.attribute(
- utils.py_attr('def'), lambda p: p.method)
- py_attrs = utils.attribute(
- utils.py_attr('attrs'), lambda p: p.expression)
- py_content = utils.attribute(
- utils.py_attr('content'), lambda p: p.output)
- py_replace = utils.attribute(
- utils.py_attr('replace'), lambda p: p.output)
- py_strip = utils.attribute(
- utils.py_attr('strip'), lambda p: p.expression)
- xi_href = None
- xi_parse = None
-
-class MetaElement(XHTMLElement, translation.MetaElement):
- pass
-
-class PyElement(XHTMLElement):
- py_strip = utils.attribute("strip", lambda p: p.expression, u"")
-
-class PyIfElement(PyElement):
- py_if = utils.attribute("test", lambda p: p.expression)
-
-class PyForElement(PyElement):
- py_for = utils.attribute("each", lambda p: p.definition)
-
-class PyWithElement(PyElement):
- py_with = utils.attribute(
- "vars", lambda p: expressions.python_translation.definitions)
-
-class PyDefElement(PyElement):
- py_def = utils.attribute("function", lambda p: p.method)
-
-class PyMatchElement(PyElement):
- py_match = utils.attribute("path")
-
-class XiIncludeElement(XHTMLElement):
- xi_href = utils.attribute(
- "href", lambda p: expressions.StringTranslation(p).expression)
- xi_parse = utils.attribute("parse", default="xml")
-
-class GenshiParser(etree.Parser):
- """ The parser implementation for Genshi templates """
- element_mapping = {
- config.XHTML_NS: {None: XHTMLElement},
- config.META_NS: {None: MetaElement},
- config.XI_NS: {'include': XiIncludeElement},
- config.PY_NS: {'if': PyIfElement,
- 'for': PyForElement,
- 'def': PyDefElement,
- 'with': PyWithElement,
- 'match': PyMatchElement}}
Deleted: Sandbox/Chameleon/src/chameleon/core/genshi.txt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/genshi.txt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/genshi.txt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,439 +0,0 @@
-Genshi
-======
-
- >>> from z3c.pt.testing import render_genshi
-
-py:if
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <div py:if="False">
- ... <p>Bar</p>
- ... </div>
- ... <div py:if="True">
- ... <p>Foo</p>
- ... </div>
- ... <py:if test="False">
- ... <b>Bar</b>
- ... </py:if>
- ... <py:if test="True">
- ... <b>Foo</b>
- ... </py:if>
- ... </div>""")
- <div>
- <div>
- <p>Foo</p>
- </div>
- <BLANKLINE>
- <b>Foo</b>
- <BLANKLINE>
- </div>
-
-py:choose, py:when, py:otherwise
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <div py:choose="">
- ... <span py:when="0 == 1">0</span>
- ... <span py:when="1 == 1">1</span>
- ... <div>
- ... <span py:when="2 == 2">2</span>
- ... <span py:when="2 == 3">3</span>
- ... <div py:choose="1">
- ... <b py:when="1">3</b>
- ... <b py:when="2">4</b>
- ... </div>
- ... </div>
- ... <span py:otherwise="">3</span>
- ... <div py:choose="1">
- ... <span py:when="0">1</span>
- ... <span py:otherwise="">1</span>
- ... </div>
- ... <div py:choose="">
- ... <span py:when="0 == 1">1</span>
- ... <span py:otherwise="">2</span>
- ... </div>
- ... </div>
- ... </div>""")
- <div>
- <div>
- <span>1</span>
- <div>
- <span>2</span>
- <div>
- <b>3</b>
- </div>
- </div>
- <div>
- <span>1</span>
- </div>
- <div>
- <span>2</span>
- </div>
- </div>
- </div>
-
-py:for
-
- >>> print render_genshi("""\
- ... <ul xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <li py:for="item in range(3)">${item}</li>
- ... <py:for each="item in range(3, 5)">
- ... <li>${item}</li>
- ... </py:for>
- ... </ul>""")
- <ul>
- <li>0</li>
- <li>1</li>
- <li>2</li>
- <li>3</li>
- <li>4</li>
- </ul>
-
-py:def
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <p py:def="greeting(name)" class="greeting">
- ... Hello, ${name}!
- ... </p>
- ... ${greeting('world')}
- ... ${greeting('everyone else')}
- ... <py:def function="goodbye(name)">
- ... <p class="goodbye">Goodbye, ${name}!</p>
- ... </py:def>
- ... ${goodbye('world')}
- ... ${goodbye('everyone')}
- ... </div>""")
- <div>
- <p class="greeting">
- Hello, world!
- </p>
- <BLANKLINE>
- <p class="greeting">
- Hello, everyone else!
- </p>
- <BLANKLINE>
- <BLANKLINE>
- <p class="goodbye">Goodbye, world!</p>
- <BLANKLINE>
- <BLANKLINE>
- <BLANKLINE>
- <p class="goodbye">Goodbye, everyone!</p>
- <BLANKLINE>
- <BLANKLINE>
- </div>
-
-py:with
-
- >>> def quote():
- ... return dict(author=u"Some name", quote=u"Some random quote")
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <span py:with="x=2; y=7; z=x+10">${x} ${y} ${z}</span>
- ... <py:with vars="x=4; y=3; z=x+5">${x} ${y} ${z}</py:with>
- ... <blockquote py:with="q=quote()">
- ... "${q["quote"]} <em>${q["author"]}</em>
- ... </blockquote>
- ... </div>""", quote=quote)
- <div>
- <span>2 7 12</span>
- 4 3 9
- <blockquote>
- "Some random quote <em>Some name</em>
- </blockquote>
- </div>
-
-
-py:attrs
-
- >>> print render_genshi("""\
- ... <ul xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <li class="expand" py:attrs="{'class': 'collapse'}">Bar</li>
- ... <li class="expand" py:attrs="d">Bar</li>
- ... </ul>""", d=dict({'class': u'\u1234'}))
- <ul>
- <li class="collapse">Bar</li>
- <li class="á´">Bar</li>
- </ul>
-
-py:content, py:replace
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <span py:content="'Hello, world!'" />
- ... <span py:replace="'Goodbye, world!'" />
- ... </div>""")
- <div>
- <span>Hello, world!</span>
- Goodbye, world!
- </div>
-
-py:strip
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <span py:strip="True"><b>foo</b></span>
- ... </div>""")
- <div>
- <b>foo</b>
- </div>
-
-py:match
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <span py:match=".//xmlns:greeting">
- ... Hello, ${select('@name')[0]}!
- ... </span>
- ... <py:match path=".//xmlns:farewell">
- ... <span>Goodbye, ${select('@name')[0]}!</span>
- ... </py:match>
- ... <greeting name="dude" />
- ... <farewell name="dude" />
- ... </div>""")
- <div>
- <span>
- Hello, dude!
- </span>
- <BLANKLINE>
- <BLANKLINE>
- <span>Goodbye, dude!</span>
- <BLANKLINE>
- <BLANKLINE>
- </div>
-
-:: Genshi variable interpolation (${<exp>} notation)
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <span>inter${'pol' + 'ati'}on</span>is ${int('test') | 'convenient'}!
- ... <span>${'a'}${'b'}${'c'} ${'d'}</span>
- ... <span py:with="hello='Hello'" class="${hello} World!" />
- ... <span class="my-${'class'} item${'Last'}" />
- ... <a href="${ltr.href}" class="${ltr.iscurrent}">${ltr.letter}</a>
- ... <span style="position: ${'abs'}olute"
- ... class="my-${int('test') | 'class'} item${'Last'}" />
- ... </div>""", ltr={'letter': 'A', 'href': '?title=A', 'iscurrent': 'current'})
- <div>
- <span>interpolation</span>is convenient!
- <span>abc d</span>
- <span class="Hello World!" />
- <span class="my-class itemLast" />
- <a href="?title=A" class="current">A</a>
- <span style="position: absolute" class="my-class itemLast" />
- </div>
-
-:: Simple variable names do not need { .. }. From `py:with specs`_.
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <span py:with="y=7; z=x+10">$x $y $z</span>
- ... </div>""", x=42)
- <div>
- <span>42 7 52</span>
- </div>
-
-:: Genshi variable interpolation and unicode values
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml">
- ... <img alt="${'La Peña'}" />
- ... <img alt="Hello ${'La Peña'}" />
- ... <img alt="La Peña, oh ${'La Peña'}" />
- ... ${unicode('La Pe\xc3\xb1a', 'utf-8').encode('utf-8')}
- ... <img alt="${unicode('La Pe\xc3\xb1a', 'utf-8').encode('utf-8')}" />
- ... <img alt="Hello ${unicode('La Pe\xc3\xb1a', 'utf-8').encode('utf-8')}!" />
- ... </div>""", encoding='utf-8')
- <div>
- <img alt="La Peña" />
- <img alt="Hello La Peña" />
- <img alt="La Peña, oh La Peña" />
- La Peña
- <img alt="La Peña" />
- <img alt="Hello La Peña!" />
- </div>
-
-:: Unicode combined with attribute expansion
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml">
- ... <img alt="La Peña" />
- ... <img alt="${alt}" />
- ... </div>""", alt=unicode("La Pe\xc3\xb1a", 'utf-8'))
- <div>
- <img alt="La Peña" />
- <img alt="La Peña" />
- </div>
-
-:: Variables containing quotes
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml">
- ... <strong>"${quote}"</strong>
- ... </div>""", quote="Hello, World!")
- <div>
- <strong>"Hello, World!"</strong>
- </div>
-
-:: Variables containing markup
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml">
- ... ${message}
- ... </div>""", message="Hello, <em>World</em>!")
- <div>
- Hello, <em>World</em>!
- </div>
-
-:: Variable expansion must preserve XML validity
-
- >>> from z3c.pt import config
- >>> config.VALIDATION = True
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml">
- ... ${message}
- ... </div>""", message="Hello, <em>World!")
- Traceback (most recent call last):
- ...
- ValidationError: Insertion of 'Hello, <em>World!' is not allowed.
-
- >>> config.VALIDATION = False
-
-:: Unless we are in a CDATA block
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml">
- ... /* <![CDATA[ */
- ... ${message}
- ... /* ]]> */
- ... </div>""", message="Hello, <em>World!")
- <div>
- /* <![CDATA[ */
- Hello, <em>World!
- /* ]]> */
- </div>
-
-:: HTML comments
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <!-- a comment -->
- ... <!-- a multi-
- ... line comment -->
- ... <!-- a comment with an ${'expression'} -->
- ... </div>""")
- <div>
- <!-- a comment -->
- <!-- a multi-
- line comment -->
- <!-- a comment with an expression -->
- </div>
-
-:: z3c.pt used to forget to output the ]; after the for loop
-
- >>> print render_genshi("""\
- ... <script xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/"
- ... type="text/javascript">
- ... var brands = [
- ... <py:for each="brand in []">
- ... { value : "${brand['id']}", "title" : "${brand['title']}" },
- ... </py:for>
- ... ];
- ... </script>""")
- <script type="text/javascript">
- var brands = [
- ];
- </script>
-
-:: Strange looping behaviour
-
- >>> brands=[dict(id=1, title="One"),
- ... dict(id=2, title="Two"),
- ... dict(id=3, title="Three")]
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <script type="text/javascript">
- ... var brands = [
- ... <py:for each="brand in brands">
- ... { value : "${brand['id']}", title : "${brand['title']}" },
- ... </py:for>
- ... ];
- ...
- ... $(document.ready(function() {
- ... alert("Hello, World");
- ... });
- ... </script>
- ... </div>""", brands=brands)
- <div>
- <script type="text/javascript">
- var brands = [
- { value : "1", title : "One" },
- { value : "2", title : "Two" },
- { value : "3", title : "Three" },
- ];
- <BLANKLINE>
- $(document.ready(function() {
- alert("Hello, World");
- });
- </script>
- </div>
-
-:: Very basic recursing
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <ul py:def="rendermenu(menu)" py:if="menu">
- ... ${rendermenu([])}
- ... </ul>
- ... </div>""")
- <div>
- </div>
-
-:: Slightly more complex recursive function calls
-
- >>> print render_genshi("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <ul py:def="rendermenu(menu)">
- ... <li py:for="entry in menu"
- ... py:attrs="{'class' : entry['current'] and 'current' or None}">
- ... <a py:attrs="dict(href=entry['url'])"
- ... py:content="entry['title']">Merken</a>
- ... ${rendermenu(entry.get('children', []))}
- ... </li>
- ... </ul>
- ... ${rendermenu(menu)}
- ... </div>""", menu=[dict(title=u"Menu entry", url="/test", current=True)])
- <div>
- <ul>
- <li class="current">
- <a href="/test">Menu entry</a>
- <ul>
- <BLANKLINE>
- </ul>
- <BLANKLINE>
- </li>
- <BLANKLINE>
- </ul>
- <BLANKLINE>
- </div>
-
-.. _py:with specs: http://genshi.edgewall.org/wiki/Documentation/0.4.x/xml-templates.html#py-with
-
Deleted: Sandbox/Chameleon/src/chameleon/core/i18n.txt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/i18n.txt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/i18n.txt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,275 +0,0 @@
-i18n
-----
-
-This document highlights the i18n-support in the engine. The
-implementation is based on this document:
-
- * http://wiki.zope.org/zope3/ZPTInternationalizationSupport
-
-With the exception of i18n:data and i18n:source, the implementation is
-complete.
-
-Let's provide German mock translations for all msgids:
-
- >>> from zope import component
- >>> from zope import interface
-
- >>> from zope.i18n.interfaces import ITranslationDomain
- >>> class MockTranslationDomain(object):
- ... interface.implements(ITranslationDomain)
- ...
- ... def translate(self, msgid, mapping=None, context=None,
- ... target_language=None, default=None):
- ... if target_language != 'de':
- ... return default
- ...
- ... return "Mock translation of '%s'." % msgid
-
- >>> td = MockTranslationDomain()
- >>> component.provideUtility(td, ITranslationDomain, name="test")
-
-Translation of tag contents
----------------------------
-
-First, a simple example:
-
- >>> body = """\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:i18n="http://xml.zope.org/namespaces/i18n">
- ... <span i18n:domain="test" i18n:translate="test_msgid">
- ... Default
- ... </span>
- ... </div>"""
-
-First we need to turn the template into a callable:
-
- >>> from z3c.pt.pagetemplate import PageTemplate
- >>> template = PageTemplate(body)
-
-Let's try rendering this template without passing a target language.
-
- >>> print template.render()
- <div>
- <span>
- Default
- </span>
- </div>
-
-Now we'll render the template again---passing German as the language.
-
- >>> print template.render(target_language='de')
- <div>
- <span>Mock translation of 'test_msgid'.</span>
- </div>
-
-Let's try infering the translation message id from the tag body.
-
- >>> body = """\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:i18n="http://xml.zope.org/namespaces/i18n">
- ... <span i18n:domain="test" i18n:translate="">
- ... Default
- ... </span>
- ... </div>"""
-
-Not passing a language:
-
- >>> template = PageTemplate(body)
- >>> print template.render()
- <div>
- <span>
- Default
- </span>
- </div>
-
-Passing German:
-
- >>> print template.render(target_language='de')
- <div>
- <span>Mock translation of 'Default'.</span>
- </div>
-
-We could also add a named block inside the tag.
-
- >>> body = """\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:i18n="http://xml.zope.org/namespaces/i18n">
- ... <p i18n:domain="test" i18n:translate="">
- ... <span i18n:name="count">18</span> bananas.
- ... </p>
- ... </div>"""
-
- >>> template = PageTemplate(body)
- >>> print template.render()
- <div>
- <p>
- <span>18</span> bananas.
- </p>
- </div>
-
- >>> print template.render(target_language='de')
- <div>
- <p>Mock translation of '${count} bananas.'.</p>
- </div>
-
-Translation of tag attributes
------------------------------
-
-A simple example to start with.
-
- >>> body = """\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:i18n="http://xml.zope.org/namespaces/i18n">
- ... <span i18n:domain="test" title="Simple Title" i18n:attributes="title">
- ... Default
- ... </span>
- ... </div>"""
-
-Not passing a language:
-
- >>> template = PageTemplate(body)
- >>> print template.render()
- <div>
- <span title="Simple Title">
- Default
- </span>
- </div>
-
-Passing German:
-
- >>> print template.render(target_language='de')
- <div>
- <span title="Mock translation of 'Simple Title'.">
- Default
- </span>
- </div>
-
-Use an explicit msgid:
-
- >>> body = """\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:i18n="http://xml.zope.org/namespaces/i18n">
- ... <span i18n:domain="test" title="Simple Title"
- ... i18n:attributes="title title_simple">
- ... Default
- ... </span>
- ... </div>"""
-
-Not passing a language:
-
- >>> template = PageTemplate(body)
- >>> print template.render()
- <div>
- <span title="Simple Title">
- Default
- </span>
- </div>
-
-Passing German:
-
- >>> print template.render(target_language='de')
- <div>
- <span title="Mock translation of 'title_simple'.">
- Default
- </span>
- </div>
-
-Use an explicit msgid with a trailing semicolon.
-
- >>> body = """\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:i18n="http://xml.zope.org/namespaces/i18n">
- ... <span i18n:domain="test" title="Simple Title"
- ... i18n:attributes="title title_simple;">
- ... Default
- ... </span>
- ... </div>"""
-
-Not passing a language:
-
- >>> template = PageTemplate(body)
- >>> print template.render()
- <div>
- <span title="Simple Title">
- Default
- </span>
- </div>
-
-Passing German:
-
- >>> print template.render(target_language='de')
- <div>
- <span title="Mock translation of 'title_simple'.">
- Default
- </span>
- </div>
-
-Use multiple attributes on the same tag.
-
- >>> body = """\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:i18n="http://xml.zope.org/namespaces/i18n">
- ... <span i18n:domain="test" title="Simple Title"
- ... longdesc="A not so short description."
- ... i18n:attributes="title title_simple; longdesc desc_short">
- ... Default
- ... </span>
- ... </div>"""
-
-Not passing a language:
-
- >>> template = PageTemplate(body)
- >>> print template.render()
- <div>
- <span title="Simple Title" longdesc="A not so short description.">
- Default
- </span>
- </div>
-
-Passing German:
-
- >>> print template.render(target_language='de')
- <div>
- <span title="Mock translation of 'title_simple'."
- longdesc="Mock translation of 'desc_short'.">
- Default
- </span>
- </div>
-
-Translation of tag content and tag attributes
----------------------------------------------
-
-A simple example to start with.
-
- >>> body = """\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:i18n="http://xml.zope.org/namespaces/i18n"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <span i18n:domain="test" i18n:translate="tid"
- ... title="Title" i18n:attributes="title aid">
- ... Default, "default", 'default'
- ... </span>
- ... <span i18n:domain="test" i18n:translate=""
- ... tal:content="string:tid">
- ... Default, "default", 'default'
- ... </span>
- ... </div>"""
-
-Not passing a language:
-
- >>> template = PageTemplate(body)
- >>> print template.render()
- <div>
- <span title="Title">
- Default, "default", 'default'
- </span>
- <span>tid</span>
- </div>
-
-Passing German:
-
- >>> print template.render(target_language='de')
- <div>
- <span title="Mock translation of 'aid'.">Mock translation of 'tid'.</span>
- <span>Mock translation of 'tid'.</span>
- </div>
Modified: Sandbox/Chameleon/src/chameleon/core/loader.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/loader.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/loader.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,7 +1,5 @@
import errno
import os.path
-from z3c.pt.pagetemplate import PageTemplateFile
-from z3c.pt.texttemplate import TextTemplateFile
def cache(func):
def load(self, *args):
@@ -28,7 +26,7 @@
self.registry = {}
@cache
- def _load(self, filename, klass):
+ def load(self, filename, klass):
if os.path.isabs(filename):
return klass(filename, self.parser)
@@ -43,9 +41,3 @@
raise ValueError("Can not find template %s" % filename)
- def load_page(self, filename):
- return self._load(filename, PageTemplateFile)
-
- def load_text(self, filename):
- return self._load(filename, TextTemplateFile)
-
Deleted: Sandbox/Chameleon/src/chameleon/core/pagetemplate.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/pagetemplate.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/pagetemplate.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,125 +0,0 @@
-import zope.i18n
-
-import template
-import config
-import zpt
-import sys
-import os
-
-def prepare_language_support(**kwargs):
- target_language = kwargs.get('target_language')
-
- if config.DISABLE_I18N:
- if target_language:
- del kwargs['target_language']
- return
-
- if not target_language:
- context = kwargs.get(config.SYMBOLS.i18n_context)
- target_language = zope.i18n.negotiate(context)
-
- if target_language:
- kwargs['target_language'] = target_language
-
-class PageTemplate(template.BaseTemplate):
- __doc__ = template.BaseTemplate.__doc__ # for Sphinx autodoc
-
- default_parser = zpt.ZopePageTemplateParser()
-
- def __init__(self, body, parser=None, format=None, doctype=None):
- if parser is None:
- parser = self.default_parser
- super(PageTemplate, self).__init__(body, parser, format, doctype)
-
- def render(self, **kwargs):
- prepare_language_support(**kwargs)
- return super(PageTemplate, self).render(**kwargs)
-
-class PageTemplateFile(template.BaseTemplateFile):
- __doc__ = template.BaseTemplateFile.__doc__ # for Sphinx autodoc
-
- default_parser = zpt.ZopePageTemplateParser()
-
- def __init__(self, filename, parser=None, format=None,
- doctype=None, **kwargs):
- if parser is None:
- parser = self.default_parser
- super(PageTemplateFile, self).__init__(filename, parser, format,
- doctype, **kwargs)
-
- def render(self, **kwargs):
- prepare_language_support(**kwargs)
- return super(PageTemplateFile, self).render(**kwargs)
-
-class ZopePageTemplate(PageTemplate):
- default_parser = zpt.ZopePageTemplateParser(default_expression='path')
-
-class ZopePageTemplateFile(PageTemplateFile):
- default_parser = zpt.ZopePageTemplateParser(default_expression='path')
-
-class ViewPageTemplate(property):
- """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 __init__(self, body, **kwargs):
- self.template = ZopePageTemplate(body, **kwargs)
- property.__init__(self, self.bind)
-
- def bind(self, view, request=None, macro=None, global_scope=True):
- def render(**kwargs):
- template = self.template
-
- parameters = dict(
- view=view,
- context=view.context,
- request=request or view.request,
- template=template,
- options=kwargs)
-
- if macro is None:
- return template.render(**parameters)
- else:
- return template.render_macro(
- macro, global_scope=global_scope, parameters=parameters)
-
- return render
-
- @property
- def macros(self):
- return self.template.macros
-
-class ViewPageTemplateFile(ViewPageTemplate):
- """If ``filename`` is a relative path, the module path of the
- class where the instance is used to get an absolute path."""
-
- 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['__name__']
-
- if package_name != self.__module__:
- break
-
- module = sys.modules[package_name]
- try:
- path = module.__path__[0]
- except AttributeError:
- path = module.__file__
- path = path[:path.rfind(os.sep)]
-
- filename = path + os.sep + filename
-
- self.template = ZopePageTemplateFile(filename, **kwargs)
- property.__init__(self, self.bind)
-
- def __call__(self, view, **kwargs):
- template = self.bind(view)
- return template(**kwargs)
Modified: Sandbox/Chameleon/src/chameleon/core/template.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/template.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/template.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -4,7 +4,7 @@
import filecache
import translation
-class BaseTemplate(object):
+class Template(object):
"""Constructs a template object using the template language
defined by ``parser`` (``ZopePageTemplateParser`` or
``GenshiParser`` as of this writing). Must be passed an input
@@ -76,7 +76,7 @@
def __call__(self, **kwargs):
return self.render(**kwargs)
-class BaseTemplateFile(BaseTemplate):
+class TemplateFile(Template):
"""Constructs a template object using the template language
defined by ``parser``. Must be passed an absolute (or
current-working-directory-relative) filename as ``filename``. If
@@ -88,7 +88,7 @@
def __init__(self, filename, parser, format=None, doctype=None,
auto_reload=False):
- BaseTemplate.__init__(
+ Template.__init__(
self, None, parser, format=format, doctype=doctype)
self.auto_reload = auto_reload
@@ -148,11 +148,11 @@
if self.auto_reload and self._v_last_read != self.mtime():
self.read()
- return BaseTemplate.cook_check(self, **kwargs)
+ return Template.cook_check(self, **kwargs)
def render(self, **kwargs):
kwargs[config.SYMBOLS.xincludes] = self.xincludes
- return super(BaseTemplateFile, self).render(**kwargs)
+ return super(TemplateFile, self).render(**kwargs)
def mtime(self):
try:
Modified: Sandbox/Chameleon/src/chameleon/core/template.txt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/template.txt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/template.txt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,29 +1,27 @@
Template classes
================
-This section demonstrates the high-level template classes.
-
-z3c.pt.pagetemplate.PageTemplate
+chameleon.core.template.Template
--------------------------------
- >>> from z3c.pt.pagetemplate import PageTemplate
- >>> from z3c.pt.testing import mock_parser
+ >>> from chameleon.core.template import Template
+ >>> from chameleon.core.testing import mock_parser
- >>> print PageTemplate("""\
+ >>> print Template("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... Hello World!
- ... </div>""")()
+ ... </div>""", mock_parser)()
<div>
Hello World!
</div>
-z3c.pt.pagetemplate.PageTemplateFile
+chameleon.core.template.TemplateFile
------------------------------------
- >>> from z3c.pt.pagetemplate import PageTemplateFile
- >>> from z3c.pt import tests
+ >>> from chameleon.core.template import TemplateFile
+ >>> from chameleon.core import tests
>>> path = tests.__path__[0]
- >>> t = PageTemplateFile(path+'/helloworld.pt')
+ >>> t = TemplateFile(path+'/helloworld.pt', mock_parser)
>>> print t()
<div>
Hello World!
@@ -33,256 +31,3 @@
>>> t.filename.startswith(os.sep)
True
-z3c.pt.pagetemplate.ViewPageTemplate
-------------------------------------
-
- >>> from z3c.pt.pagetemplate import ViewPageTemplate
-
- >>> class ViewPageTemplateView(object):
- ... __call__ = ViewPageTemplate(
- ... open(path+'/view.pt').read())
- ... request = u'request'
- ... context = u'context'
-
- >>> view = ViewPageTemplateView()
-
- >>> print view(test=u'test')
- <div>
- <span><ViewPageTemplateView object at ...></span>
- <span>context</span>
- <span>request</span>
- <span>test</span>
- </div>
-
-z3c.pt.pagetemplate.ViewPageTemplateFile
-----------------------------------------
-
- >>> from z3c.pt.pagetemplate import ViewPageTemplateFile
-
- >>> class ViewPageTemplateView(object):
- ... __call__ = ViewPageTemplateFile(path+'/view.pt')
- ... request = u'request'
- ... context = u'context'
-
- >>> view = ViewPageTemplateView()
-
- >>> print view(test=u'test')
- <div>
- <span><ViewPageTemplateView object at ...></span>
- <span>context</span>
- <span>request</span>
- <span>test</span>
- </div>
-
-z3c.pt.texttemplate.ViewTextTemplate
-------------------------------------
-
- >>> from z3c.pt.texttemplate import ViewTextTemplate
-
- >>> class ViewTextTemplateView(object):
- ... __call__ = ViewTextTemplate(open(path+'/view.css').read())
- ... request = u'request'
- ... context = u'context'
-
- >>> view = ViewTextTemplateView()
-
- >>> print view(color=u'#ccc')
- #region {
- background: #ccc;
- }
-
-z3c.pt.texttemplate.ViewTextTemplateFile
-----------------------------------------
-
- >>> from z3c.pt.texttemplate import ViewTextTemplateFile
-
- >>> class ViewTextTemplateView(object):
- ... __call__ = ViewTextTemplateFile(path+'/view.css')
- ... request = u'request'
- ... context = u'context'
-
- >>> view = ViewTextTemplateView()
-
- >>> print view(color=u'#ccc')
- #region {
- background: #ccc;
- }
-
-Compiler integration
---------------------
-
-Certain constructs require close collaboration between the template
-compiler and the page template classes.
-
-py:match integration
-
- >>> from z3c.pt.genshi import GenshiParser
-
- >>> print PageTemplate("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:py="http://genshi.edgewall.org/">
- ... <py:match path=".//xmlns:greeting">Hello ${select('@name')[0]}!</py:match>
- ... <greeting name="World" />
- ... </div>
- ... """, parser=GenshiParser())()
- <div>
- Hello World!
- <BLANKLINE>
- </div>
-
-metal:define-macro, metal:use-macro
-
- >>> template1 = PageTemplate("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal"
- ... xmlns:metal="http://xml.zope.org/namespaces/metal">
- ... <div metal:define-macro="greeting">
- ... Hello, ${name}!
- ... <span tal:define="global name 'earth'">
- ... Hello, ${name}!
- ... </span>
- ... Hello, ${name}!
- ... </div>
- ... </div>""")
-
- >>> template2 = PageTemplate("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal"
- ... xmlns:metal="http://xml.zope.org/namespaces/metal">
- ... <div tal:define="name 'world'">
- ... <div metal:use-macro="template1.macros['greeting']" />
- ... Hello, ${name}!
- ... </div>
- ... Hello, ${name}!
- ... </div>""")
-
- >>> print template2(template1=template1)
- <div>
- <div>
- <div>
- Hello, world!
- <span>
- Hello, earth!
- </span>
- Hello, earth!
- </div>
- <BLANKLINE>
- Hello, world!
- </div>
- Hello, earth!
- </div>
-
-metal:define-macro, metal:use-macro, metal:define-slot, metal:fill-slot
-
- >>> main = PageTemplate("""\
- ... <html xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal"
- ... xmlns:metal="http://xml.zope.org/namespaces/metal"
- ... metal:define-macro="master">
- ... <div metal:define-slot="content">
- ... I will be replaced
- ... </div>
- ... </html>""")
-
- >>> content = PageTemplate("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal"
- ... xmlns:metal="http://xml.zope.org/namespaces/metal"
- ... metal:use-macro="main.macros['master']">
- ... <div metal:fill-slot="content">
- ... I replace you.
- ... </div>
- ... </div>""")
-
- >>> print content(main=main)
- <html>
- <div>
- I replace you.
- </div>
- </html>
-
-xi:include
-
- >>> from z3c.pt.template import BaseTemplateFile
- >>> template1 = BaseTemplateFile(path+"/xinclude1.pt", mock_parser)
- >>> print template1()
- <div>
- <div>
- <span>Hello, world!</span>
- </div>
- </div>
-
-:: XInclude in Genshi
-
-When using XInclude-statements in Genshi, macro-definitions are
-carried over from the included template. This is demonstrated below.
-
- >>> template2 = BaseTemplateFile(path+"/xinclude3.pt", GenshiParser())
- >>> print template2()
- <div>
- <BLANKLINE>
- <BLANKLINE>
- <p class="greeting">
- Hello, world!
- </p>
- <BLANKLINE>
- </div>
-
-Before we proceed, we reduce and restore the underlying byte-code
-template.
-
- >>> from cPickle import dumps, loads
- >>> for registry in (template1.registry, template2.registry):
- ... for key, bct in registry.items():
- ... registry[key] = loads(dumps(bct))
-
- >>> print template2()
- <div>
- <BLANKLINE>
- <BLANKLINE>
- <p class="greeting">
- Hello, world!
- </p>
- <BLANKLINE>
- </div>
-
-
-Error handling
---------------
-
-When an exception is raised which does not expose a bug in the TAL
-translation machinery, we expect the exception to contain the part of
-the template source that caused the exception.
-
-Exception while evaluating expression:
-
- >>> PageTemplate("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <span tal:content="range()" />
- ... </div>""").render()
- Traceback (most recent call last):
- ...
- TypeError: range expected at least 1 arguments, got 0
-
-Exception while evaluating definition:
-
- >>> PageTemplate("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <span tal:define="dummy range()" />
- ... </div>""").render()
- Traceback (most recent call last):
- ...
- TypeError: range expected at least 1 arguments, got 0
-
-Exception while evaluating interpolation:
-
- >>> PageTemplate("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <span>${range()}</span>
- ... </div>""").render()
- Traceback (most recent call last):
- ...
- TypeError: range expected at least 1 arguments, got 0
Modified: Sandbox/Chameleon/src/chameleon/core/testing.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/testing.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/testing.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -7,9 +7,6 @@
import config
import utils
-import zpt
-import genshi
-
from StringIO import StringIO
from cPickle import dumps, loads
@@ -47,33 +44,6 @@
template = compiler(parameters=sorted(kwargs.keys()))
return template.render(**kwargs)
-def render_zpt(body, **kwargs):
- compiler = TestCompiler(
- body, zpt.ZopePageTemplateParser(), implicit_doctype=doctypes.xhtml)
- template = compiler(parameters=sorted(kwargs.keys()))
- return template.render(**kwargs)
-
-def render_genshi(body, encoding=None, **kwargs):
- compiler = TestCompiler(
- body, genshi.GenshiParser(),
- encoding=encoding, implicit_doctype=doctypes.xhtml)
- template = compiler(parameters=sorted(kwargs.keys()))
- kwargs.update(template.selectors)
- return template.render(**kwargs)
-
-class MockTemplate(object):
- def __init__(self, body, parser):
- self.body = body
- self.parser = parser
-
- @property
- def macros(self):
- def render(name, parameters={}):
- compiler = TestCompiler(self.body, self.parser)
- template = compiler(macro=name, parameters=parameters)
- return template.render(**parameters)
- return template.Macros(render)
-
class MockElement(translation.Element, translation.VariableInterpolation):
translator = expressions.python_translation
@@ -134,3 +104,26 @@
config.XI_NS: {None: MockXiElement}}
mock_parser = MockParser()
+
+class MockTemplate(object):
+ def __init__(self, body, parser=mock_parser, doctype=None):
+ self.body = body
+ self.parser = parser
+ self.doctype = doctype
+
+ @property
+ def macros(self):
+ def render(name, parameters={}):
+ compiler = TestCompiler(self.body, self.parser)
+ template = compiler(macro=name, parameters=parameters)
+ return template.render(**parameters)
+ return template.Macros(render)
+
+ def render(self, **kwargs):
+ compiler = TestCompiler(
+ self.body, self.parser,
+ implicit_doctype=doctypes.xhtml, explicit_doctype=self.doctype)
+ template = compiler(parameters=sorted(kwargs.keys()))
+ return template.render(**kwargs)
+
+ __call__ = render
Modified: Sandbox/Chameleon/src/chameleon/core/tests/test_doctests.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/tests/test_doctests.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/tests/test_doctests.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -5,31 +5,28 @@
zope.testing.doctest.NORMALIZE_WHITESPACE)
import zope.component.testing
-import zope.configuration.xmlconfig
-import z3c.pt.config
+import chameleon.core.config
def setUp(suite):
zope.component.testing.setUp(suite)
- zope.configuration.xmlconfig.XMLConfig('configure.zcml', z3c.pt)()
-
+
def test_suite():
- filesuites = ('zpt.txt', 'genshi.txt', 'template.txt',
- 'i18n.txt', 'codegen.txt', 'translation.txt')
- testsuites = ('z3c.pt.translation', 'z3c.pt.clauses', 'z3c.pt.expressions')
+ filesuites = 'template.txt', 'codegen.txt', 'translation.txt'
+ testsuites = 'translation', 'clauses', 'expressions'
- z3c.pt.config.DISK_CACHE = False
+ chameleon.core.config.DISK_CACHE = False
return unittest.TestSuite(
[zope.testing.doctest.DocTestSuite(
- doctest, optionflags=OPTIONFLAGS,
+ "chameleon.core."+doctest, optionflags=OPTIONFLAGS,
setUp=setUp, tearDown=zope.component.testing.tearDown) \
for doctest in testsuites] +
[zope.testing.doctest.DocFileSuite(
doctest, optionflags=OPTIONFLAGS,
setUp=setUp, tearDown=zope.component.testing.tearDown,
- package="z3c.pt") for doctest in filesuites]
+ package="chameleon.core") for doctest in filesuites]
)
if __name__ == '__main__':
Modified: Sandbox/Chameleon/src/chameleon/core/tests/test_edgecases.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/tests/test_edgecases.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/tests/test_edgecases.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -13,10 +13,8 @@
PlacelessSetup.tearDown(self)
def test_it(self):
- import z3c.pt
- from zope.configuration import xmlconfig
- xmlconfig.file('configure.zcml', z3c.pt)
- from z3c.pt.pagetemplate import PageTemplate
+ import chameleon.core
+ from chameleon.core.testing import MockTemplate
body = u"""\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
@@ -30,88 +28,9 @@
<html xmlns="http://www.w3.org/1999/xhtml">
foo \xa9
</html>"""
- t = PageTemplate(body)
+ t = MockTemplate(body)
self.assertEqual(norm(t.render(foo=u'foo')), norm(expected))
-class TestUnicodeAttributeLiteral(unittest.TestCase, PlacelessSetup):
- def setUp(self):
- PlacelessSetup.setUp(self)
-
- def tearDown(self):
- PlacelessSetup.tearDown(self)
-
- def test_it(self):
- import z3c.pt
- from zope.configuration import xmlconfig
- xmlconfig.file('configure.zcml', z3c.pt)
- from z3c.pt.pagetemplate import PageTemplate
- body = u"""\
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <div id="${foo}"/>
- </html>
- """
- expected = u"""\
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <div id="\xa9"/>
- </html>"""
- t = PageTemplate(body)
- c = unicode('\xc2\xa9', 'utf-8')
- self.assertEqual(norm(t.render(foo=c)), norm(expected))
-
- def test_torture(self):
- import z3c.pt
- from z3c.pt.genshi import GenshiParser
- from zope.configuration import xmlconfig
- xmlconfig.file('configure.zcml', z3c.pt)
- from z3c.pt.pagetemplate import PageTemplate
- body = u"""\
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml"
- xmlns:py="http://genshi.edgewall.org/">
- <title>\xa9</title>
- <div id="${foo}" py:attrs="dict(label=foo)"/>
- </html>
- """
- expected = u"""\
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <title>\xa9</title>
- <div label="\xa9" id="\xa9"/>
- </html>"""
- t = PageTemplate(body, parser=GenshiParser())
- c = unicode('\xc2\xa9', 'utf-8')
- self.assertEqual(norm(t.render(foo=c)), norm(expected))
-
-class TestZCMLActionsPickleable(unittest.TestCase, PlacelessSetup):
- # see also
- # http://groups.google.com/group/z3c_pt/browse_thread/thread/bd0cc94b5fd40ae0?hl=en
- def setUp(self):
- PlacelessSetup.setUp(self)
-
- def tearDown(self):
- PlacelessSetup.tearDown(self)
-
- def test_registry_actions_can_be_pickled_and_unpickled(self):
- from z3c import pt as package
- from zope.configuration import config
- from zope.configuration import xmlconfig
- context = config.ConfigurationMachine()
- xmlconfig.registerCommonDirectives(context)
- context.package = package
- xmlconfig.include(context, 'configure.zcml', package)
- context.execute_actions(clear=False)
- actions = context.actions
- import pickle
- dumped = pickle.dumps(actions, -1)
- new = pickle.loads(dumped)
- self.assertEqual(len(actions), len(new))
-
class TestExplicitDoctypes(unittest.TestCase, PlacelessSetup):
def setUp(self):
PlacelessSetup.setUp(self)
@@ -120,11 +39,9 @@
PlacelessSetup.tearDown(self)
def test_doctype_declared_in_constructor_adds_doctype(self):
- import z3c.pt
- from zope.configuration import xmlconfig
- xmlconfig.file('configure.zcml', z3c.pt)
- from z3c.pt.pagetemplate import PageTemplate
- from z3c.pt import doctypes
+ import chameleon.core
+ from chameleon.core.testing import MockTemplate
+ from chameleon.core import doctypes
body = u"""\
<html xmlns="http://www.w3.org/1999/xhtml">
</html>
@@ -134,15 +51,13 @@
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
</html>"""
- t = PageTemplate(body, doctype=doctypes.xhtml_strict)
+ t = MockTemplate(body, doctype=doctypes.xhtml_strict)
self.assertEqual(norm(t.render()), norm(expected))
def test_doctype_declared_in_constructor_overrides_template_doctype(self):
- import z3c.pt
- from zope.configuration import xmlconfig
- xmlconfig.file('configure.zcml', z3c.pt)
- from z3c.pt.pagetemplate import PageTemplate
- from z3c.pt import doctypes
+ import chameleon.core
+ from chameleon.core.testing import MockTemplate
+ from chameleon.core import doctypes
body = u"""\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
@@ -154,15 +69,13 @@
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
</html>"""
- t = PageTemplate(body, doctype=doctypes.xhtml_strict)
+ t = MockTemplate(body, doctype=doctypes.xhtml_strict)
self.assertEqual(norm(t.render()), norm(expected))
def test_doctype_assigned_to_instance_overrides_constructor_doctype(self):
- import z3c.pt
- from zope.configuration import xmlconfig
- xmlconfig.file('configure.zcml', z3c.pt)
- from z3c.pt.pagetemplate import PageTemplate
- from z3c.pt import doctypes
+ import chameleon.core
+ from chameleon.core.testing import MockTemplate
+ from chameleon.core import doctypes
body = u"""\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
@@ -174,16 +87,14 @@
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
</html>"""
- t = PageTemplate(body, doctype=doctypes.html)
+ t = MockTemplate(body, doctype=doctypes.html)
t.doctype = doctypes.html
self.assertEqual(norm(t.render()), norm(expected))
def test_no_doctype_overrides_parsed_doctype(self):
- import z3c.pt
- from zope.configuration import xmlconfig
- xmlconfig.file('configure.zcml', z3c.pt)
- from z3c.pt.pagetemplate import PageTemplate
- from z3c.pt import doctypes
+ import chameleon.core
+ from chameleon.core.testing import MockTemplate
+ from chameleon.core import doctypes
body = u"""\
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
@@ -193,7 +104,7 @@
expected = u"""\
<html xmlns="http://www.w3.org/1999/xhtml">
</html>"""
- t = PageTemplate(body, doctype=doctypes.no_doctype)
+ t = MockTemplate(body, doctype=doctypes.no_doctype)
self.assertEqual(norm(t.render()), norm(expected))
def norm(s):
Modified: Sandbox/Chameleon/src/chameleon/core/tests/test_loader.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/tests/test_loader.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/tests/test_loader.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,12 +1,14 @@
import unittest
+from chameleon.core import template
+
class LoadTests:
def _makeOne(self, search_path=None, auto_reload=False, cachedir=None):
klass = self._getTargetClass()
return klass(search_path, auto_reload, cachedir)
def _getTargetClass(self):
- from z3c.pt.loader import TemplateLoader
+ from chameleon.core.loader import TemplateLoader
return TemplateLoader
def test_load_relative(self):
@@ -14,8 +16,8 @@
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'))
+ result = self._load(loader, 'helloworld.pt')
+ self.assertEqual(result.filename, os.path.join(here, 'helloworld.pt'))
def test_consecutive_loads(self):
import os
@@ -23,31 +25,27 @@
loader = self._makeOne(search_path = [here])
self.assertTrue(
- self._load(loader, 'view.pt') is self._load(loader, 'view.pt'))
+ self._load(loader, 'helloworld.pt') is self._load(loader, 'helloworld.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'))
+ result = self._load(loader, 'helloworld.pt')
+ self.assertEqual(result.filename, os.path.join(here, 'helloworld.pt'))
def test_load_abs(self):
import os
here = os.path.dirname(__file__)
loader = self._makeOne()
- abs = os.path.join(here, 'view.pt')
+ abs = os.path.join(here, 'helloworld.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)
+ return loader.load(filename, template.TemplateFile)
-class LoadTextTests(unittest.TestCase, LoadTests):
- def _load(self, loader, filename):
- return loader.load_text(filename)
-
def test_suite():
import sys
return unittest.findTestCases(sys.modules[__name__])
Deleted: Sandbox/Chameleon/src/chameleon/core/tests/view.css
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/tests/view.css 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/tests/view.css 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,3 +0,0 @@
-#region {
- background: ${options.color};
-}
\ No newline at end of file
Deleted: Sandbox/Chameleon/src/chameleon/core/tests/view.pt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/tests/view.pt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/tests/view.pt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,7 +0,0 @@
-<div xmlns="http://www.w3.org/1999/xhtml"
- xmlns:tal="http://xml.zope.org/namespaces/tal">
- <span tal:content="nocall: view" />
- <span tal:content="context" />
- <span tal:content="request" />
- <span tal:content="options/test" />
-</div>
Deleted: Sandbox/Chameleon/src/chameleon/core/tests/xinclude1.pt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/tests/xinclude1.pt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/tests/xinclude1.pt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,4 +0,0 @@
-<div xmlns="http://www.w3.org/1999/xhtml"
- xmlns:xi="http://www.w3.org/2001/XInclude">
- <xi:include href="xinclude${1+1}.pt" />
-</div>
Deleted: Sandbox/Chameleon/src/chameleon/core/tests/xinclude2.pt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/tests/xinclude2.pt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/tests/xinclude2.pt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,3 +0,0 @@
-<div xmlns="http://www.w3.org/1999/xhtml">
- <span>Hello, world!</span>
-</div>
Deleted: Sandbox/Chameleon/src/chameleon/core/tests/xinclude3.pt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/tests/xinclude3.pt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/tests/xinclude3.pt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,6 +0,0 @@
-<div xmlns="http://www.w3.org/1999/xhtml"
- xmlns:py="http://genshi.edgewall.org/"
- xmlns:xi="http://www.w3.org/2001/XInclude">
- <xi:include href="xinclude${4}.pt" />
- ${greeting('world')}
-</div>
Deleted: Sandbox/Chameleon/src/chameleon/core/tests/xinclude4.pt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/tests/xinclude4.pt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/tests/xinclude4.pt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,7 +0,0 @@
-<div xmlns="http://www.w3.org/1999/xhtml"
- xmlns:py="http://genshi.edgewall.org/"
- py:strip="">
- <p py:def="greeting(name)" class="greeting">
- Hello, ${name}!
- </p>
-</div>
Deleted: Sandbox/Chameleon/src/chameleon/core/texttemplate.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/texttemplate.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/texttemplate.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,29 +0,0 @@
-import pagetemplate
-import translation
-
-class TextTemplate(pagetemplate.PageTemplate):
- __doc__ = pagetemplate.PageTemplate.__doc__ # for Sphinx autodoc
- format = 'text'
-
-class TextTemplateFile(pagetemplate.PageTemplateFile):
- __doc__ = pagetemplate.PageTemplateFile.__doc__ # for Sphinx autodoc
- format = 'text'
-
-class ViewTextTemplate(property):
- def __init__(self, body):
- self.template = TextTemplate(body)
- property.__init__(self, self.render)
-
- def render(self, view):
- def template(**kwargs):
- return self.template.render(view=view,
- context=view.context,
- request=view.request,
- _context=view.request,
- options=kwargs)
- return template
-
-class ViewTextTemplateFile(ViewTextTemplate):
- def __init__(self, filename):
- self.template = TextTemplateFile(filename)
- property.__init__(self, self.render)
Modified: Sandbox/Chameleon/src/chameleon/core/translation.txt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/translation.txt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/translation.txt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -3,7 +3,7 @@
This document contains functional template tests.
- >>> from z3c.pt.testing import render_xhtml
+ >>> from chameleon.core.testing import render_xhtml
XHTML
-----
@@ -115,7 +115,7 @@
Text templates
--------------
- >>> from z3c.pt.testing import render_text
+ >>> from chameleon.core.testing import render_text
An example with a CSS stylesheet document:
@@ -142,7 +142,7 @@
To facilitate disk-caching, template instances can be pickled.
- >>> from z3c.pt.testing import compile_xhtml
+ >>> from chameleon.core.testing import compile_xhtml
>>> template = compile_xhtml("""\
... <div xmlns="http://www.w3.org/1999/xhtml">
... Hello World!
@@ -155,7 +155,7 @@
Check that we're getting a template object back.
>>> template
- <ByteCodeTemplate parser="z3c.pt.testing.MockParser">
+ <ByteCodeTemplate parser="chameleon.core.testing.MockParser">
Let's try and render the template.
Modified: Sandbox/Chameleon/src/chameleon/core/utils.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/utils.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/utils.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -15,7 +15,7 @@
unicode_required_flag = False
except UnicodeEncodeError:
unicode_required_flag = True
- log = logging.getLogger('z3c.pt')
+ log = logging.getLogger('Chameleon')
log.info("Default system encoding is set to '%s'; "
"the template engine will perform better if "
"an encoding that coerces gracefully to "
Deleted: Sandbox/Chameleon/src/chameleon/core/zpt.py
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/zpt.py 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/zpt.py 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,231 +0,0 @@
-from zope import component
-
-import translation
-import interfaces
-import itertools
-import utils
-import config
-import etree
-
-class ZopePageTemplateElement(
- translation.Element, translation.VariableInterpolation,
- translation.NativeAttributePrefixSupport):
- """Zope Page Template element.
-
- Implements the ZPT subset of the attribute template language.
- """
-
- class node(translation.Node):
- @property
- def omit(self):
- if self.element.tal_omit is not None:
- return self.element.tal_omit or True
- if self.element.meta_omit is not None:
- return self.element.meta_omit or True
- if self.element.tal_replace or self.element.meta_replace:
- return True
- if self.element.metal_use or self.element.metal_fillslot:
- return True
-
- @property
- def define(self):
- return self.element.tal_define
-
- @property
- def condition(self):
- return self.element.tal_condition
-
- @property
- def repeat(self):
- return self.element.tal_repeat
-
- @property
- def content(self):
- return self.element.tal_content or self.element.tal_replace or \
- self.element.meta_replace
-
- @property
- def skip(self):
- if self.define_slot:
- variable = self.symbols.slot + self.define_slot
- if variable in itertools.chain(*self.stream.scope):
- return True
-
- return self.content or \
- self.use_macro or self.translate is not None
-
- @property
- def dynamic_attributes(self):
- return (self.element.tal_attributes or ()) + \
- (self.element.meta_attributes or ())
-
- @property
- def translated_attributes(self):
- return self.element.i18n_attributes
-
- @property
- def static_attributes(self):
- return utils.get_attributes_from_namespace(
- self.element, config.XHTML_NS)
-
- @property
- def translate(self):
- return self.element.i18n_translate
-
- @property
- def translation_name(self):
- return self.element.i18n_name
-
- @property
- def translation_domain(self):
- return self.element.i18n_domain
-
- @property
- def use_macro(self):
- return self.element.metal_use
-
- @property
- def define_macro(self):
- return self.element.metal_define
-
- @property
- def define_slot(self):
- return self.element.metal_defineslot
-
- @property
- def fill_slot(self):
- return self.element.metal_fillslot
-
- @property
- def cdata(self):
- return self.element.meta_cdata
-
- @property
- def default_expression(self):
- return self.element.tal_default_expression
-
- node = property(node)
-
- @property
- def translator(self):
- while self.node.default_expression is None:
- self = self.getparent()
- if self is None:
- raise ValueError("Default expression not set.")
-
- return component.getUtility(
- interfaces.IExpressionTranslation, name=self.node.default_expression)
-
- def update(self):
- translation.NativeAttributePrefixSupport.update(self)
- translation.VariableInterpolation.update(self)
-
-class XHTMLElement(ZopePageTemplateElement):
- """XHTML namespace element."""
-
- tal_define = utils.attribute(
- utils.tal_attr('define'), lambda p: p.definitions)
- tal_condition = utils.attribute(
- utils.tal_attr('condition'), lambda p: p.expression)
- tal_repeat = utils.attribute(
- utils.tal_attr('repeat'), lambda p: p.definition)
- tal_attributes = utils.attribute(
- utils.tal_attr('attributes'), lambda p: p.definitions)
- tal_content = utils.attribute(
- utils.tal_attr('content'), lambda p: p.output)
- tal_replace = utils.attribute(
- utils.tal_attr('replace'), lambda p: p.output)
- tal_omit = utils.attribute(
- utils.tal_attr('omit-tag'), lambda p: p.expression)
- tal_default_expression = utils.attribute(
- utils.tal_attr('default-expression'), encoding='ascii')
- metal_define = utils.attribute(
- utils.metal_attr('define-macro'), lambda p: p.method)
- metal_use = utils.attribute(
- utils.metal_attr('use-macro'), lambda p: p.expression)
- metal_fillslot = utils.attribute(
- utils.metal_attr('fill-slot'))
- metal_defineslot = utils.attribute(
- utils.metal_attr('define-slot'))
- i18n_translate = utils.attribute(
- utils.i18n_attr('translate'))
- i18n_attributes = utils.attribute(
- utils.i18n_attr('attributes'), lambda p: p.mapping)
- i18n_domain = utils.attribute(
- utils.i18n_attr('domain'))
- i18n_name = utils.attribute(
- utils.i18n_attr('name'))
-
-class MetaElement(XHTMLElement, translation.MetaElement):
- pass
-
-class TALElement(ZopePageTemplateElement):
- """TAL namespace element."""
-
- tal_define = utils.attribute("define", lambda p: p.definitions)
- tal_condition = utils.attribute("condition", lambda p: p.expression)
- tal_replace = utils.attribute("replace", lambda p: p.output)
- tal_repeat = utils.attribute("repeat", lambda p: p.definition)
- tal_attributes = utils.attribute("attributes", lambda p: p.expression)
- tal_content = utils.attribute("content", lambda p: p.output)
- tal_omit = utils.attribute("omit-tag", lambda p: p.expression, u"")
- tal_default_expression = utils.attribute(
- 'default-expression')
- tal_cdata = utils.attribute("cdata")
-
- metal_define = None
- metal_use = None
- metal_fillslot = None
- metal_defineslot = None
- i18n_domain = None
- i18n_translate = None
- i18n_attributes = None
-
-class METALElement(ZopePageTemplateElement):
- """METAL namespace element."""
-
- tal_define = None
- tal_condition = None
- tal_replace = None
- tal_content = None
- tal_repeat = None
- tal_attributes = None
- tal_omit = True
- tal_default_expression = None
- tal_cdata = None
- metal_define = utils.attribute('define-macro', lambda p: p.method)
- metal_use = utils.attribute('use-macro', lambda p: p.expression)
- metal_fillslot = utils.attribute('fill-slot')
- metal_defineslot = utils.attribute('define-slot')
- i18n_domain = None
- i18n_translate = None
- i18n_attributes = None
-
-class ZopePageTemplateParser(etree.Parser):
- """ The parser implementation for ZPT """
- element_mapping = {
- config.XHTML_NS: {None: XHTMLElement},
- config.META_NS: {None: MetaElement},
- config.TAL_NS: {None: TALElement},
- config.METAL_NS: {None: METALElement}}
-
- default_expression = 'python'
-
- def __init__(self, default_expression=None):
- if default_expression is not None:
- self.default_expression = default_expression
-
- def parse(self, body):
- root, doctype = super(ZopePageTemplateParser, self).parse(body)
- # if a default expression is not set explicitly in the
- # template, use the TAL-attribute ``default-expression``
- # to set it
- if utils.get_namespace(root) == config.TAL_NS:
- tag = 'default-expression'
- else:
- tag = utils.tal_attr('default-expression')
-
- if not root.attrib.get(tag):
- root.attrib[tag] = self.default_expression
-
- return root, doctype
Deleted: Sandbox/Chameleon/src/chameleon/core/zpt.txt
===================================================================
--- Sandbox/Chameleon/src/z3c/pt/zpt.txt 2008-09-15 16:18:35 UTC (rev 91162)
+++ Sandbox/Chameleon/src/chameleon/core/zpt.txt 2008-09-15 21:10:51 UTC (rev 91165)
@@ -1,409 +0,0 @@
-Zope Page Templates (ZPT)
-=========================
-
- >>> from z3c.pt.testing import render_zpt
-
-TAL
----
-
-:: Namespace elements
-
- >>> print render_zpt("""\
- ... <tal:block xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... Hello, world!
- ... </tal:block>""")
- <BLANKLINE>
- Hello, world!
- <BLANKLINE>
-
-tal:define, tal:attributes, tal:contents
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <span id="test"
- ... class="dummy"
- ... onclick=""
- ... tal:define="a 'abc'"
- ... tal:attributes="class 'def' + a; style 'hij'; onClick 'alert();'"
- ... tal:content="a + 'ghi'" />
- ... <span tal:replace="'Hello World!'">Hello <b>Universe</b>!</span>
- ... <span tal:replace="'Hello World!'"><b>Hello Universe!</b></span>
- ... <span tal:content="None" />
- ... </div>""")
- <div>
- <span class="defabc" style="hij" onclick="alert();" id="test">abcghi</span>
- Hello World!
- Hello World!
- <span></span>
- </div>
-
-tal:attributes 'checked' and 'selected' toggles
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <option tal:attributes="selected True"/>
- ... <option tal:attributes="selected None"/>
- ... <input tal:attributes="checked True"/>
- ... <input tal:attributes="checked False"/>
- ... </div>""")
- <div>
- <option selected="True" />
- <option />
- <input checked="True" />
- <input />
- </div>
-
-tal:repeat
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <ul>
- ... <li tal:repeat="i range(5)"><span tal:replace="'Item ' + str(i) + ')'" /></li>
- ... </ul>
- ... </div>""")
- <div>
- <ul>
- <li>Item 0)</li>
- <li>Item 1)</li>
- <li>Item 2)</li>
- <li>Item 3)</li>
- <li>Item 4)</li>
- </ul>
- </div>
-
-tal:repeat (repeat-variable)
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <ul>
- ... <li tal:repeat="i range(3)"><span tal:replace="str(i) + ' ' + str(repeat['i'].even())" /></li>
- ... </ul>
- ... </div>""")
- <div>
- <ul>
- <li>0 True</li>
- <li>1 False</li>
- <li>2 True</li>
- </ul>
- </div>
-
-tal:condition
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <div tal:condition="True">
- ... Show me!
- ... </div>
- ... <div tal:condition="False">
- ... Do not show me!
- ... </div>
- ... </div>""")
- <div>
- <div>
- Show me!
- </div>
- </div>
-
-:: HTML comments
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <!-- a comment -->
- ... <!-- a multi-
- ... line comment -->
- ... <!-- a comment with an ${'expression'} -->
- ... </div>""")
- <div>
- <!-- a comment -->
- <!-- a multi-
- line comment -->
- <!-- a comment with an expression -->
- </div>
-
-:: TAL elements with namespace prefix
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <tal:example replace="'Hello World!'" />
- ... <tal:example tal:replace="'Hello World!'" />
- ... <tal:div content="'Hello World!'" />
- ... <tal:multiple repeat="i range(3)" replace="i" />
- ... <tal:div condition="True">True</tal:div>
- ... </div>""")
- <div>
- Hello World!
- Hello World!
- Hello World!
- 0
- 1
- 2
- True
- </div>
-
-tal:omit-tag
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <p tal:omit-tag="">No paragraph here.</p>
- ... <p tal:omit-tag="True">No paragraph here either.</p>
- ... <p tal:omit-tag="False">A paragraph here.</p>
- ... </div>""")
- <div>
- No paragraph here.
- No paragraph here either.
- <p>A paragraph here.</p>
- </div>
-
-:: Unicode with dynamic attributes and content
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <img tal:attributes="title '%sHello%s' % (chr(60), chr(62))" />
- ... <span tal:replace="structure '%sbr /%s' % (chr(60), chr(62))" />
- ... <span tal:replace="'%sbr /%s' % (chr(60), chr(62))" />
- ... <span tal:content="unicode('La Pe\xc3\xb1a', 'utf-8')" />
- ... </div>""")
- <div>
- <img title="<Hello>" />
- <br />
- <br />
- <span>La Peña</span>
- </div>
-
-:: Using the "path:" expression
-
- >>> class Test(object):
- ... greeting = u'Hello'
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <span tal:replace="path: test1/greeting" />
- ... <span tal:replace="path: test2/greeting" />
- ... </div>""", request=object(),
- ... test1={'greeting': u'Hello'}, test2=Test())
- <div>
- Hello
- Hello
- </div>
-
-:: Using the "string:" expression
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <span tal:replace="string:${greeting}, world!" />
- ... <img tal:attributes="alt string:Leonardo da Vinci;; Musee du Louvre, 1503;
- ... title string:Mona Lisa" />
- ... </div>""", request=object(), greeting=u'Hello')
- <div>
- Hello, world!
- <img alt="Leonardo da Vinci; Musee du Louvre, 1503" title="Mona Lisa" />
- </div>
-
-:: Using the "provider:" expression
-
- >>> class Context(object): pass
- >>> class Request(object): pass
- >>> class View(object): pass
-
-This directive renders a content provider; let's define and register a
-content provider which allows us to verify the functionality of the
-expression.
-
- >>> from zope.contentprovider.interfaces import IContentProvider
- >>> from zope import component
- >>> from zope import interface
-
- >>> class DummyContentProvider(object):
- ... component.adapts(Context, Request, View)
- ... interface.implements(IContentProvider)
- ...
- ... def __init__(self, context, request, view):
- ... self.context = context
- ... self.request = request
- ... self.view = view
- ...
- ... def update(self):
- ... self.updated = True
- ...
- ... def render(self):
- ... return type(self.context), type(self.request), \
- ... type(self.view), self.updated
-
- >>> component.provideAdapter(
- ... DummyContentProvider, name="test")
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <span tal:replace="structure provider:test" />
- ... </div>""", context=Context(), request=Request(), view=View())
- <div>
- (<class 'Context'>, <class 'Request'>, <class 'View'>, True)
- </div>
-
-:: Setting the default expression
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <div tal:default-expression="path">
- ... <span tal:replace="test/greeting" />
- ... </div>
- ... </div>""", request=object(), test={'greeting': u'Hello'})
- <div>
- <div>
- Hello
- </div>
- </div>
-
-:: Using different expressions with try-except operator (|)
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <tal:path-expression-testing
- ... define="request object();
- ... mydict {'a': 1, 'c': {'a': 2}}">
- ... <div tal:default-expression="path">
- ... <span tal:replace="mydict/a" />
- ... <span tal:replace="mydict/b|mydict/a" />
- ... <span tal:replace="mydict/c/a" />
- ... <span tal:replace="python: 5+5" />
- ... </div>
- ... <span tal:replace="path: mydict/a" />
- ... <span tal:replace="python: 1+1" />
- ... <span tal:replace="path: mydict/b|True" />
- ... <span tal:replace="int('a')|path: mydict/a" />
- ... </tal:path-expression-testing>
- ... </div>""")
- <div>
- <BLANKLINE>
- <div>
- 1
- 1
- 2
- 10
- </div>
- 1
- 2
- True
- 1
- <BLANKLINE>
- </div>
-
-:: Using TAL pragmas "nocall" and "structure"
-
- >>> print render_zpt("""\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal">
- ... <span tal:default-expression="path"
- ... tal:replace="structure nocall: dir" />
- ... <span tal:replace="structure dir" />
- ... </div>""", request=object())
- <div>
- <built-in function dir>
- <built-in function dir>
- </div>
-
-METAL
------
-
-metal:define-macro, metal:use-macro
-
- >>> body = """\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal"
- ... xmlns:metal="http://xml.zope.org/namespaces/metal">
- ... <div class="greeting" metal:define-macro="greeting">
- ... Hello, ${name|string:earth}!
- ... </div>
- ... <div tal:define="name 'world'">
- ... <div metal:use-macro="template.macros['greeting']" />
- ... </div>
- ... </div>"""
-
- >>> from z3c.pt.testing import MockTemplate
- >>> from z3c.pt.zpt import ZopePageTemplateParser
-
- >>> template = MockTemplate(body, ZopePageTemplateParser())
- >>> print render_zpt(body, template=template)
- <div>
- <div class="greeting">
- Hello, earth!
- </div>
- <div>
- <div class="greeting">
- Hello, world!
- </div>
- <BLANKLINE>
- </div>
- </div>
-
-metal:define-slot, metal:fill-slot
-
- >>> body = """\
- ... <div xmlns="http://www.w3.org/1999/xhtml"
- ... xmlns:tal="http://xml.zope.org/namespaces/tal"
- ... xmlns:metal="http://xml.zope.org/namespaces/metal">
- ... <div metal:define-macro="greeting">
- ... Hey, <span class="name" metal:define-slot="name">
- ... a <em>stranger!</em></span>
- ... </div>
- ... <div metal:use-macro="template.macros['greeting']">
- ... This will be omitted
- ... <span metal:fill-slot="name">earth!</span>
- ... </div>
- ... <div metal:use-macro="template.macros['greeting']">
- ... <div>
- ... <metal:earth fill-slot="name">earth!</metal:earth>
- ... </div>
- ... </div>
- ... <div metal:use-macro="template.macros['greeting']">
- ... <!-- display fallback greeting -->
- ... </div>
- ... <div metal:use-macro="template.macros['greeting']">
- ... <span metal:fill-slot="dummy">dummy!</span>
- ... </div>
- ... </div>"""
-
- >>> from z3c.pt.testing import MockTemplate
-
- >>> template = MockTemplate(body, ZopePageTemplateParser())
- >>> print render_zpt(body, template=template)
- <div>
- <div>
- Hey, <span class="name">
- a <em>stranger!</em></span>
- </div>
- <div>
- Hey, <span class="name">earth!</span>
- </div>
- <BLANKLINE>
- <div>
- Hey, <span class="name">earth!</span>
- </div>
- <BLANKLINE>
- <div>
- Hey, <span class="name">
- a <em>stranger!</em></span>
- </div>
- <BLANKLINE>
- <div>
- Hey, <span class="name">
- a <em>stranger!</em></span>
- </div>
- <BLANKLINE>
- </div>
-
-
More information about the Checkins
mailing list