2
from zope.traversing.interfaces import IPathAdapter
4
class AdapterNamespaces(object):
5
"""Simulate tales function namespaces with adapter lookup.
7
When we are asked for a namespace, we return an object that
8
actually computes an adapter when called:
10
To demonstrate this, we need to register an adapter:
14
>>> zope.component.getGlobalSiteManager().registerAdapter(
15
... adapter1, [zope.interface.Interface], IPathAdapter, 'a1')
17
Now, with this adapter in place, we can try out the namespaces:
20
>>> namespaces = AdapterNamespaces()
21
>>> namespace = namespaces['a1']
24
>>> namespace = namespaces['a2']
26
Traceback (most recent call last):
34
def __getitem__(self, name):
35
namespace = self.namespaces.get(name)
37
def namespace(object):
39
return zope.component.getAdapter(object, IPathAdapter, name)
40
except zope.component.ComponentLookupError:
43
self.namespaces[name] = namespace
47
def registerFunctionNamespace(self, namespacename, namespacecallable):
48
"""Register a function namespace
50
namespace - a string containing the name of the namespace to
53
namespacecallable - a callable object which takes the following
56
context - the object on which the functions
57
provided by this namespace will
60
This callable should return an object which
61
can be traversed to get the functions provided
62
by the this namespace.
66
class stringFuncs(object):
68
def __init__(self,context):
69
self.context = str(context)
72
return self.context.upper()
75
return self.context.lower()
77
engine.registerFunctionNamespace('string',stringFuncs)
79
self.namespaces[namespacename] = namespacecallable
82
def getFunctionNamespace(self, namespacename):
83
""" Returns the function namespace """
84
return self.namespaces[namespacename]
87
# If zope.app.pagetemplates is available, use the adapter
88
# registered with the main zope.app.pagetemplates engine so that
89
# we don't need to re-register them.
90
from zope.app.pagetemplates.engine import Engine
91
function_namespaces = Engine.namespaces
92
except (ImportError, AttributeError):
93
function_namespaces = AdapterNamespaces()