zope.viewlet-3.7.2/0000755000175000017500000000000011376754277014105 5ustar tseavertseaverzope.viewlet-3.7.2/buildout.cfg0000644000175000017500000000014511376754171016406 0ustar tseavertseaver[buildout] develop = . parts = test [test] recipe = zc.recipe.testrunner eggs = zope.viewlet [test] zope.viewlet-3.7.2/COPYRIGHT.txt0000644000175000017500000000004011376754171016201 0ustar tseavertseaverZope Foundation and Contributorszope.viewlet-3.7.2/CHANGES.txt0000644000175000017500000000321111376754171015704 0ustar tseavertseaver======= CHANGES ======= 3.7.2 (2010-05-25) ------------------ - Fixed unit tests broken under Python 2.4 by the switch to the standard library ``doctest`` module. 3.7.1 (2010-04-30) ------------------ - Removed use of 'zope.testing.doctest' in favor of stdlib's 'doctest. - Fixed dubious quoting in metadirectives.py. Closes https://bugs.launchpad.net/zope2/+bug/143774. 3.7.0 (2009-12-22) ------------------ - Depend on zope.browserpage in favor of zope.app.pagetemplate. 3.6.1 (2009-08-29) ------------------ - Fixed unit tests in README.txt. 3.6.0 (2009-08-02) ------------------ - Optimize the the script tag for the JS viewlet. This makes YSlow happy. - Remove ZCML slugs and old zpkg-related files. - Drop all testing dependncies except ``zope.testing``. 3.5.0 (2009-01-26) ------------------ - Removed the dependency on `zope.app.publisher` by moving four simple helper functions into this package and making the interface for describing the ZCML content provider directive explicit. - Typo fix in CSSViewlet docstring. 3.4.2 (2008-01-24) ------------------ - Re-release of 3.4.1 because of brown bag release. 3.4.1 (2008-01-21) ------------------ - bugfix, implemented missing __contains__ method in IViewletManager - implemented additional viewlet managers offering weight ordered sorting - implemented additional viewlet managers offering conditional filtering 3.4.1a (2007-4-22) ------------------ - bugfix, added a missing ',' behind zope.i18nmessageid. - recreated the README.txt removing everything except for the overview. 3.4.0 (2007-10-10) ------------------ - Initial release independent of the main Zope tree. zope.viewlet-3.7.2/setup.cfg0000644000175000017500000000007311376754277015726 0ustar tseavertseaver[egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 zope.viewlet-3.7.2/README.txt0000644000175000017500000000011511376754171015571 0ustar tseavertseaverViewlets provide a generic framework for building pluggable user interfaces. zope.viewlet-3.7.2/PKG-INFO0000644000175000017500000017667211376754277015225 0ustar tseavertseaverMetadata-Version: 1.0 Name: zope.viewlet Version: 3.7.2 Summary: Zope Viewlets Home-page: http://pypi.python.org/pypi/zope.viewlet Author: Zope Foundation and Contributors Author-email: zope-dev@zope.org License: ZPL 2.1 Description: Viewlets provide a generic framework for building pluggable user interfaces. Detailed Documentation ********************** ============================= Viewlets and Viewlet Managers ============================= Let's start with some motivation. Using content providers allows us to insert one piece of HTML content. In most Web development, however, you are often interested in defining some sort of region and then allow developers to register content for those regions. >>> from zope.viewlet import interfaces Design Notes ------------ As mentioned above, besides inserting snippets of HTML at places, we more frequently want to define a region in our page and allow specialized content providers to be inserted based on configuration. Those specialized content providers are known as viewlets and are only available inside viewlet managers, which are just a more complex example of content providers. Unfortunately, the Java world does not implement this layer separately. The viewlet manager is most similar to a Java "channel", but we decided against using this name, since it is very generic and not very meaningful. The viewlet has no Java counterpart, since Java does not implement content providers using a component architecture and thus does not register content providers specifically for viewlet managers, which I believe makes the Java implementation less useful as a generic concept. In fact, the main design goal in the Java world is the implementation of reusable and sharable portlets. The scope for Zope 3 is larger, since we want to provide a generic framework for building pluggable user interfaces. The Viewlet Manager ------------------- In this implementation of viewlets, those regions are just content providers called viewlet managers that manage a special type of content providers known as viewlets. Every viewlet manager handles the viewlets registered for it: >>> class ILeftColumn(interfaces.IViewletManager): ... """Viewlet manager located in the left column.""" You can then create a viewlet manager using this interface now: >>> from zope.viewlet import manager >>> LeftColumn = manager.ViewletManager('left', ILeftColumn) Now we have to instantiate it: >>> import zope.interface >>> class Content(object): ... zope.interface.implements(zope.interface.Interface) >>> content = Content() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> from zope.publisher.interfaces.browser import IBrowserView >>> class View(object): ... zope.interface.implements(IBrowserView) ... def __init__(self, context, request): ... pass >>> view = View(content, request) >>> leftColumn = LeftColumn(content, request, view) So initially nothing gets rendered: >>> leftColumn.update() >>> leftColumn.render() u'' But now we register some viewlets for the manager >>> import zope.component >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> class WeatherBox(object): ... zope.interface.implements(interfaces.IViewlet) ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... ... def update(self): ... pass ... ... def render(self): ... return u'
It is sunny today!
' >>> # Create a security checker for viewlets. >>> from zope.security.checker import NamesChecker, defineChecker >>> viewletChecker = NamesChecker(('update', 'render')) >>> defineChecker(WeatherBox, viewletChecker) >>> zope.component.provideAdapter( ... WeatherBox, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, ILeftColumn), ... interfaces.IViewlet, name='weather') >>> from zope.location.interfaces import ILocation >>> class SportBox(object): ... zope.interface.implements(interfaces.IViewlet, ... ILocation) ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... ... def update(self): ... pass ... ... def render(self): ... return u'
Patriots (23) : Steelers (7)
' >>> defineChecker(SportBox, viewletChecker) >>> zope.component.provideAdapter( ... SportBox, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, ILeftColumn), ... interfaces.IViewlet, name='sport') and thus the left column is filled. Note that also events get fired before viewlets are updated. We register a simple handler to demonstrate this behaviour. >>> from zope.contentprovider.interfaces import IBeforeUpdateEvent >>> events = [] >>> def handler(ev): ... events.append(ev) >>> zope.component.provideHandler(handler, (IBeforeUpdateEvent,)) >>> leftColumn.update() >>> [(ev, ev.object.__class__.__name__) for ev in events] [(, 'SportBox'), (, 'WeatherBox')] >>> print leftColumn.render()
Patriots (23) : Steelers (7)
It is sunny today!
But this is of course pretty lame, since there is no way of specifying how the viewlets are put together. But we have a solution. The second argument of the ``ViewletManager()`` function is a template in which we can specify how the viewlets are put together: >>> import os, tempfile >>> temp_dir = tempfile.mkdtemp() >>> leftColTemplate = os.path.join(temp_dir, 'leftCol.pt') >>> open(leftColTemplate, 'w').write(''' ...
... ...
... ''') >>> LeftColumn = manager.ViewletManager('left', ILeftColumn, ... template=leftColTemplate) >>> leftColumn = LeftColumn(content, request, view) TODO: Fix this silly thing; viewlets should be directly available. As you can see, the viewlet manager provides a global ``options/viewlets`` variable that is an iterable of all the available viewlets in the correct order: >>> leftColumn.update() >>> print leftColumn.render().strip()
Patriots (23) : Steelers (7)
It is sunny today!
If a viewlet provides ILocation the ``__name__`` attribute of the viewlet is set to the name under which the viewlet is registered. >>> [getattr(viewlet, '__name__', None) for viewlet in leftColumn.viewlets] [u'sport', None] You can also lookup the viewlets directly for management purposes: >>> leftColumn['weather'] >>> leftColumn.get('weather') The viewlet manager also provides the __contains__ method defined in IReadMapping: >>> 'weather' in leftColumn True >>> 'unknown' in leftColumn False If the viewlet is not found, then the expected behavior is provided: >>> leftColumn['stock'] Traceback (most recent call last): ... ComponentLookupError: No provider with name `stock` found. >>> leftColumn.get('stock') is None True Customizing the default Viewlet Manager --------------------------------------- One important feature of any viewlet manager is to be able to filter and sort the viewlets it is displaying. The default viewlet manager that we have been using in the tests above, supports filtering by access availability and sorting via the viewlet's ``__cmp__()`` method (default). You can easily override this default policy by providing a base viewlet manager class. In our case we will manage the viewlets using a global list: >>> shown = ['weather', 'sport'] The viewlet manager base class now uses this list: >>> class ListViewletManager(object): ... ... def filter(self, viewlets): ... viewlets = super(ListViewletManager, self).filter(viewlets) ... return [(name, viewlet) ... for name, viewlet in viewlets ... if name in shown] ... ... def sort(self, viewlets): ... viewlets = dict(viewlets) ... return [(name, viewlets[name]) for name in shown] Let's now create a new viewlet manager: >>> LeftColumn = manager.ViewletManager( ... 'left', ILeftColumn, bases=(ListViewletManager,), ... template=leftColTemplate) >>> leftColumn = LeftColumn(content, request, view) So we get the weather box first and the sport box second: >>> leftColumn.update() >>> print leftColumn.render().strip()
It is sunny today!
Patriots (23) : Steelers (7)
Now let's change the order... >>> shown.reverse() and the order should switch as well: >>> leftColumn.update() >>> print leftColumn.render().strip()
Patriots (23) : Steelers (7)
It is sunny today!
Of course, we also can remove a shown viewlet: >>> weather = shown.pop() >>> leftColumn.update() >>> print leftColumn.render().strip()
Patriots (23) : Steelers (7)
WeightOrderedViewletManager --------------------------- The weight ordered viewlet manager offers ordering viewlets by a additional weight argument. Viewlets which doesn't provide a weight attribute will get a weight of 0 (zero). Let's define a new column: >>> class IWeightedColumn(interfaces.IViewletManager): ... """Column with weighted viewlet manager.""" First register a template for the weight ordered viewlet manager: >>> weightedColTemplate = os.path.join(temp_dir, 'weightedColTemplate.pt') >>> open(weightedColTemplate, 'w').write(''' ...
... ...
... ''') And create a new weight ordered viewlet manager: >>> from zope.viewlet.manager import WeightOrderedViewletManager >>> WeightedColumn = manager.ViewletManager( ... 'left', IWeightedColumn, bases=(WeightOrderedViewletManager,), ... template=weightedColTemplate) >>> weightedColumn = WeightedColumn(content, request, view) Let's create some viewlets: >>> from zope.viewlet import viewlet >>> class FirstViewlet(viewlet.ViewletBase): ... ... weight = 1 ... ... def render(self): ... return u'
first
' >>> class SecondViewlet(viewlet.ViewletBase): ... ... weight = 2 ... ... def render(self): ... return u'
second
' >>> class ThirdViewlet(viewlet.ViewletBase): ... ... weight = 3 ... ... def render(self): ... return u'
third
' >>> class UnWeightedViewlet(viewlet.ViewletBase): ... ... def render(self): ... return u'
unweighted
' >>> defineChecker(FirstViewlet, viewletChecker) >>> defineChecker(SecondViewlet, viewletChecker) >>> defineChecker(ThirdViewlet, viewletChecker) >>> defineChecker(UnWeightedViewlet, viewletChecker) >>> zope.component.provideAdapter( ... ThirdViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='third') >>> zope.component.provideAdapter( ... FirstViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='first') >>> zope.component.provideAdapter( ... SecondViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='second') >>> zope.component.provideAdapter( ... UnWeightedViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='unweighted') And check the order: >>> weightedColumn.update() >>> print weightedColumn.render().strip()
unweighted
first
second
third
ConditionalViewletManager ------------------------- The conditional ordered viewlet manager offers ordering viewlets by a additional weight argument and filters by the available attribute if a supported by the viewlet. Viewlets which doesn't provide a available attribute will not get skipped. The default weight value for viewlets which doesn't provide a weight attribute is 0 (zero). Let's define a new column: >>> class IConditionalColumn(interfaces.IViewletManager): ... """Column with weighted viewlet manager.""" First register a template for the weight ordered viewlet manager: >>> conditionalColTemplate = os.path.join(temp_dir, ... 'conditionalColTemplate.pt') >>> open(conditionalColTemplate, 'w').write(''' ...
... ...
... ''') And create a new conditional viewlet manager: >>> from zope.viewlet.manager import ConditionalViewletManager >>> ConditionalColumn = manager.ViewletManager( ... 'left', IConditionalColumn, bases=(ConditionalViewletManager,), ... template=conditionalColTemplate) >>> conditionalColumn = ConditionalColumn(content, request, view) Let's create some viewlets. We also use the previous viewlets supporting no weight and or no available attribute: >>> from zope.viewlet import viewlet >>> class AvailableViewlet(viewlet.ViewletBase): ... ... weight = 4 ... ... available = True ... ... def render(self): ... return u'
available
' >>> class UnAvailableViewlet(viewlet.ViewletBase): ... ... weight = 5 ... ... available = False ... ... def render(self): ... return u'
not available
' >>> defineChecker(AvailableViewlet, viewletChecker) >>> defineChecker(UnAvailableViewlet, viewletChecker) >>> zope.component.provideAdapter( ... ThirdViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='third') >>> zope.component.provideAdapter( ... FirstViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='first') >>> zope.component.provideAdapter( ... SecondViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='second') >>> zope.component.provideAdapter( ... UnWeightedViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='unweighted') >>> zope.component.provideAdapter( ... AvailableViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='available') >>> zope.component.provideAdapter( ... UnAvailableViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='unavailable') And check the order: >>> conditionalColumn.update() >>> print conditionalColumn.render().strip()
unweighted
first
second
third
available
Viewlet Base Classes -------------------- To make the creation of viewlets simpler, a set of useful base classes and helper functions are provided. The first class is a base class that simply defines the constructor: >>> base = viewlet.ViewletBase('context', 'request', 'view', 'manager') >>> base.context 'context' >>> base.request 'request' >>> base.__parent__ 'view' >>> base.manager 'manager' But a default ``render()`` method implementation is not provided: >>> base.render() Traceback (most recent call last): ... NotImplementedError: `render` method must be implemented by subclass. If you have already an existing class that produces the HTML content in some method, then the ``SimpleAttributeViewlet`` might be for you, since it can be used to convert any class quickly into a viewlet: >>> class FooViewlet(viewlet.SimpleAttributeViewlet): ... __page_attribute__ = 'foo' ... ... def foo(self): ... return 'output' The `__page_attribute__` attribute provides the name of the function to call for rendering. >>> foo = FooViewlet('context', 'request', 'view', 'manager') >>> foo.foo() 'output' >>> foo.render() 'output' If you specify `render` as the attribute an error is raised to prevent infinite recursion: >>> foo.__page_attribute__ = 'render' >>> foo.render() Traceback (most recent call last): ... AttributeError: render The same is true if the specified attribute does not exist: >>> foo.__page_attribute__ = 'bar' >>> foo.render() Traceback (most recent call last): ... AttributeError: 'FooViewlet' object has no attribute 'bar' To create simple template-based viewlets you can use the ``SimpleViewletClass()`` function. This function is very similar to its view equivalent and is used by the ZCML directives to create viewlets. The result of this function call will be a fully functional viewlet class. Let's start by simply specifying a template only: >>> template = os.path.join(temp_dir, 'demoTemplate.pt') >>> open(template, 'w').write('''
contents
''') >>> Demo = viewlet.SimpleViewletClass(template) >>> print Demo(content, request, view, manager).render()
contents
Now let's additionally specify a class that can provide additional features: >>> class MyViewlet(object): ... myAttribute = 8 >>> Demo = viewlet.SimpleViewletClass(template, bases=(MyViewlet,)) >>> MyViewlet in Demo.__bases__ True >>> Demo(content, request, view, manager).myAttribute 8 The final important feature is the ability to pass in further attributes to the class: >>> Demo = viewlet.SimpleViewletClass( ... template, attributes={'here': 'now', 'lucky': 3}) >>> demo = Demo(content, request, view, manager) >>> demo.here 'now' >>> demo.lucky 3 As for all views, they must provide a name that can also be passed to the function: >>> Demo = viewlet.SimpleViewletClass(template, name='demoViewlet') >>> demo = Demo(content, request, view, manager) >>> demo.__name__ 'demoViewlet' In addition to the the generic viewlet code above, the package comes with two viewlet base classes and helper functions for inserting CSS and Javascript links into HTML headers, since those two are so very common. I am only going to demonstrate the helper functions here, since those demonstrations will fully demonstrate the functionality of the base classes as well. The viewlet will look up the resource it was given and tries to produce the absolute URL for it: >>> class JSResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/resource.js' >>> zope.component.provideAdapter( ... JSResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='resource.js') >>> JSViewlet = viewlet.JavaScriptViewlet('resource.js') >>> print JSViewlet(content, request, view, manager).render().strip() There is also a javascript viewlet base class which knows how to render more then one javascript resource file: >>> class JSSecondResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/second-resource.js' >>> zope.component.provideAdapter( ... JSSecondResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='second-resource.js') >>> JSBundleViewlet = viewlet.JavaScriptBundleViewlet(('resource.js', ... 'second-resource.js')) >>> print JSBundleViewlet(content, request, view, manager).render().strip() The same works for the CSS resource viewlet: >>> class CSSResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/resource.css' >>> zope.component.provideAdapter( ... CSSResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='resource.css') >>> CSSViewlet = viewlet.CSSViewlet('resource.css') >>> print CSSViewlet(content, request, view, manager).render().strip() You can also change the media type and the rel attribute: >>> CSSViewlet = viewlet.CSSViewlet('resource.css', media='print', rel='css') >>> print CSSViewlet(content, request, view, manager).render().strip() There is also a bundle viewlet for CSS links: >>> class CSSPrintResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/print-resource.css' >>> zope.component.provideAdapter( ... CSSPrintResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='print-resource.css') >>> items = [] >>> items.append({'path':'resource.css', 'rel':'stylesheet', 'media':'all'}) >>> items.append({'path':'print-resource.css', 'media':'print'}) >>> CSSBundleViewlet = viewlet.CSSBundleViewlet(items) >>> print CSSBundleViewlet(content, request, view, manager).render().strip() A Complex Example ----------------- The Data ~~~~~~~~ So far we have only demonstrated simple (maybe overly trivial) use cases of the viewlet system. In the following example, we are going to develop a generic contents view for files. The step is to create a file component: >>> class IFile(zope.interface.Interface): ... data = zope.interface.Attribute('Data of file.') >>> class File(object): ... zope.interface.implements(IFile) ... def __init__(self, data=''): ... self.__name__ = '' ... self.data = data Since we want to also provide the size of a file, here a simple implementation of the ``ISized`` interface: >>> from zope import size >>> class FileSized(object): ... zope.interface.implements(size.interfaces.ISized) ... zope.component.adapts(IFile) ... ... def __init__(self, file): ... self.file = file ... ... def sizeForSorting(self): ... return 'byte', len(self.file.data) ... ... def sizeForDisplay(self): ... return '%i bytes' %len(self.file.data) >>> zope.component.provideAdapter(FileSized) We also need a container to which we can add files: >>> class Container(dict): ... def __setitem__(self, name, value): ... value.__name__ = name ... super(Container, self).__setitem__(name, value) Here is some sample data: >>> container = Container() >>> container['test.txt'] = File('Hello World!') >>> container['mypage.html'] = File('Hello World!') >>> container['data.xml'] = File('Hello World!') The View ~~~~~~~~ The contents view of the container should iterate through the container and represent the files in a table: >>> contentsTemplate = os.path.join(temp_dir, 'contents.pt') >>> open(contentsTemplate, 'w').write(''' ... ... ...

Contents

...
... ... ... ''') >>> from zope.browserpage.simpleviewclass import SimpleViewClass >>> Contents = SimpleViewClass(contentsTemplate, name='contents.html') The Viewlet Manager ~~~~~~~~~~~~~~~~~~~ Now we have to write our own viewlet manager. In this case we cannot use the default implementation, since the viewlets will be looked up for each different item: >>> shownColumns = [] >>> class ContentsViewletManager(object): ... zope.interface.implements(interfaces.IViewletManager) ... index = None ... ... def __init__(self, context, request, view): ... self.context = context ... self.request = request ... self.__parent__ = view ... ... def update(self): ... rows = [] ... for name, value in self.context.items(): ... rows.append( ... [zope.component.getMultiAdapter( ... (value, self.request, self.__parent__, self), ... interfaces.IViewlet, name=colname) ... for colname in shownColumns]) ... [entry.update() for entry in rows[-1]] ... self.rows = rows ... ... def render(self, *args, **kw): ... return self.index(*args, **kw) Now we need a template to produce the contents table: >>> tableTemplate = os.path.join(temp_dir, 'table.pt') >>> open(tableTemplate, 'w').write(''' ... ... ... ... ...
... ...
... ''') From the two pieces above, we can generate the final viewlet manager class and register it (it's a bit tedious, I know): >>> from zope.browserpage import ViewPageTemplateFile >>> ContentsViewletManager = type( ... 'ContentsViewletManager', (ContentsViewletManager,), ... {'index': ViewPageTemplateFile(tableTemplate)}) >>> zope.component.provideAdapter( ... ContentsViewletManager, ... (Container, IDefaultBrowserLayer, zope.interface.Interface), ... interfaces.IViewletManager, name='contents') Since we have not defined any viewlets yet, the table is totally empty: >>> contents = Contents(container, request) >>> print contents().strip()

Contents

The Viewlets and the Final Result ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Now let's create a first viewlet for the manager... >>> class NameViewlet(object): ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... self.context = context ... ... def update(self): ... pass ... ... def render(self): ... return self.context.__name__ and register it: >>> zope.component.provideAdapter( ... NameViewlet, ... (IFile, IDefaultBrowserLayer, ... zope.interface.Interface, interfaces.IViewletManager), ... interfaces.IViewlet, name='name') Note how you register the viewlet on ``IFile`` and not on the container. Now we should be able to see the name for each file in the container: >>> print contents().strip()

Contents

Waaa, nothing there! What happened? Well, we have to tell our user preferences that we want to see the name as a column in the table: >>> shownColumns = ['name'] >>> print contents().strip()

Contents

mypage.html
data.xml
test.txt
Let's now write a second viewlet that will display the size of the object for us: >>> class SizeViewlet(object): ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... self.context = context ... ... def update(self): ... pass ... ... def render(self): ... return size.interfaces.ISized(self.context).sizeForDisplay() >>> zope.component.provideAdapter( ... SizeViewlet, ... (IFile, IDefaultBrowserLayer, ... zope.interface.Interface, interfaces.IViewletManager), ... interfaces.IViewlet, name='size') After we added it to the list of shown columns, >>> shownColumns = ['name', 'size'] we can see an entry for it: >>> print contents().strip()

Contents

mypage.html 38 bytes
data.xml 31 bytes
test.txt 12 bytes
If we switch the two columns around, >>> shownColumns = ['size', 'name'] the result will be >>> print contents().strip()

Contents

38 bytes mypage.html
31 bytes data.xml
12 bytes test.txt
Supporting Sorting ~~~~~~~~~~~~~~~~~~ Oftentimes you also want to batch and sort the entries in a table. Since those two features are not part of the view logic, they should be treated with independent components. In this example, we are going to only implement sorting using a simple utility: >>> class ISorter(zope.interface.Interface): ... ... def sort(values): ... """Sort the values.""" >>> class SortByName(object): ... zope.interface.implements(ISorter) ... ... def sort(self, values): ... return sorted(values, lambda x, y: cmp(x.__name__, y.__name__)) >>> zope.component.provideUtility(SortByName(), name='name') >>> class SortBySize(object): ... zope.interface.implements(ISorter) ... ... def sort(self, values): ... return sorted( ... values, ... lambda x, y: cmp(size.interfaces.ISized(x).sizeForSorting(), ... size.interfaces.ISized(y).sizeForSorting())) >>> zope.component.provideUtility(SortBySize(), name='size') Note that we decided to give the sorter utilities the same name as the corresponding viewlet. This convention will make our implementation of the viewlet manager much simpler: >>> sortByColumn = '' >>> class SortedContentsViewletManager(object): ... zope.interface.implements(interfaces.IViewletManager) ... index = None ... ... def __init__(self, context, request, view): ... self.context = context ... self.request = request ... self.__parent__ = view ... ... def update(self): ... values = self.context.values() ... ... if sortByColumn: ... sorter = zope.component.queryUtility(ISorter, sortByColumn) ... if sorter: ... values = sorter.sort(values) ... ... rows = [] ... for value in values: ... rows.append( ... [zope.component.getMultiAdapter( ... (value, self.request, self.__parent__, self), ... interfaces.IViewlet, name=colname) ... for colname in shownColumns]) ... [entry.update() for entry in rows[-1]] ... self.rows = rows ... ... def render(self, *args, **kw): ... return self.index(*args, **kw) As you can see, the concern of sorting is cleanly separated from generating the view code. In MVC terms that means that the controller (sort) is logically separated from the view (viewlets). Let's now do the registration dance for the new viewlet manager. We simply override the existing registration: >>> SortedContentsViewletManager = type( ... 'SortedContentsViewletManager', (SortedContentsViewletManager,), ... {'index': ViewPageTemplateFile(tableTemplate)}) >>> zope.component.provideAdapter( ... SortedContentsViewletManager, ... (Container, IDefaultBrowserLayer, zope.interface.Interface), ... interfaces.IViewletManager, name='contents') Finally we sort the contents by name: >>> shownColumns = ['name', 'size'] >>> sortByColumn = 'name' >>> print contents().strip()

Contents

data.xml 31 bytes
mypage.html 38 bytes
test.txt 12 bytes
Now let's sort by size: >>> sortByColumn = 'size' >>> print contents().strip()

Contents

test.txt 12 bytes
data.xml 31 bytes
mypage.html 38 bytes
That's it! As you can see, in a few steps we have built a pretty flexible contents view with selectable columns and sorting. However, there is a lot of room for extending this example: - Table Header: The table header cell for each column should be a different type of viewlet, but registered under the same name. The column header viewlet also adapts the container not the item. The header column should also be able to control the sorting. - Batching: A simple implementation of batching should work very similar to the sorting feature. Of course, efficient implementations should somehow combine batching and sorting more effectively. - Sorting in ascending and descending order: Currently, you can only sort from the smallest to the highest value; however, this limitation is almost superficial and can easily be removed by making the sorters a bit more flexible. - Further Columns: For a real application, you would want to implement other columns, of course. You would also probably want some sort of fallback for the case that a viewlet is not found for a particular container item and column. Cleanup ------- >>> import shutil >>> shutil.rmtree(temp_dir) ================================ The ``viewletManager`` Directive ================================ The ``viewletManager`` directive allows you to quickly register a new viewlet manager without worrying about the details of the ``adapter`` directive. Before we can use the directives, we have to register their handlers by executing the package's meta configuration: >>> from zope.configuration import xmlconfig >>> context = xmlconfig.string(''' ... ... ... ... ''') Now we can register a viewlet manager: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Let's make sure the directive has really issued a sensible adapter registration; to do that, we create some dummy content, request and view objects: >>> import zope.interface >>> class Content(object): ... zope.interface.implements(zope.interface.Interface) >>> content = Content() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> from zope.publisher.browser import BrowserView >>> view = BrowserView(content, request) Now let's lookup the manager. This particular registration is pretty boring: >>> import zope.component >>> from zope.viewlet import interfaces >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ... interfaces.IViewletManager, name='defaultmanager') >>> manager object ...> >>> interfaces.IViewletManager.providedBy(manager) True >>> manager.template is None True >>> manager.update() >>> manager.render() u'' However, this registration is not very useful, since we did specify a specific viewlet manager interface, a specific content interface, specific view or specific layer. This means that all viewlets registered will be found. The first step to effectively using the viewlet manager directive is to define a special viewlet manager interface: >>> class ILeftColumn(interfaces.IViewletManager): ... """Left column of my page.""" Now we can register register a manager providing this interface: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager object ...> >>> ILeftColumn.providedBy(manager) True >>> manager.template is None True >>> manager.update() >>> manager.render() u'' Next let's see what happens, if we specify a template for the viewlet manager: >>> import os, tempfile >>> temp_dir = tempfile.mkdtemp() >>> leftColumnTemplate = os.path.join(temp_dir, 'leftcolumn.pt') >>> open(leftColumnTemplate, 'w').write(''' ...
...
...
... ''') >>> context = xmlconfig.string(''' ... ... ... ... ''' %leftColumnTemplate, context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager object ...> >>> ILeftColumn.providedBy(manager) True >>> manager.template ...>> >>> manager.update() >>> print manager.render().strip()
Additionally you can specify a class that will serve as a base to the default viewlet manager or be a viewlet manager in its own right. In our case we will provide a custom implementation of the ``sort()`` method, which will sort by a weight attribute in the viewlet: >>> class WeightBasedSorting(object): ... def sort(self, viewlets): ... return sorted(viewlets, ... lambda x, y: cmp(x[1].weight, y[1].weight)) >>> context = xmlconfig.string(''' ... ... ... ... ''' %leftColumnTemplate, context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager object ...> >>> manager.__class__.__bases__ (, ) >>> ILeftColumn.providedBy(manager) True >>> manager.template ...>> >>> manager.update() >>> print manager.render().strip()
Finally, if a non-existent template is specified, an error is raised: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-7.8 ConfigurationError: ('No such file', '...foo.pt') ========================= The ``viewlet`` Directive ========================= Now that we have a viewlet manager, we have to register some viewlets for it. The ``viewlet`` directive is similar to the ``viewletManager`` directive, except that the viewlet is also registered for a particular manager interface, as seen below: >>> weatherTemplate = os.path.join(temp_dir, 'weather.pt') >>> open(weatherTemplate, 'w').write(''' ...
sunny
... ''') >>> context = xmlconfig.string(''' ... ... ... ... ''' % weatherTemplate, context=context) If we look into the adapter registry, we will find the viewlet: >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='weather') >>> viewlet.render().strip() u'
sunny
' >>> viewlet.extra_string_attributes u'can be specified' The manager now also gives us the output of the one and only viewlet: >>> manager.update() >>> print manager.render().strip()
sunny
Let's now ensure that we can also specify a viewlet class: >>> class Weather(object): ... weight = 0 >>> context = xmlconfig.string(''' ... ... ... ... ''' % weatherTemplate, context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='weather2') >>> viewlet().strip() u'
sunny
' Okay, so the template-driven cases work. But just specifying a class should also work: >>> class Sport(object): ... weight = 0 ... def __call__(self): ... return u'Red Sox vs. White Sox' >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, name='sport') >>> viewlet() u'Red Sox vs. White Sox' It should also be possible to specify an alternative attribute of the class to be rendered upon calling the viewlet: >>> class Stock(object): ... weight = 0 ... def getStockTicker(self): ... return u'SRC $5.19' >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='stock') >>> viewlet.render() u'SRC $5.19' A final feature the ``viewlet`` directive is that it supports the specification of any number of keyword arguments: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='stock2') >>> viewlet.weight u'8' Error Scenarios --------------- Neither the class or template have been specified: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-7.8 ConfigurationError: Must specify a class or template The specified attribute is not ``__call__``, but also a template has been specified: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-9.8 ConfigurationError: Attribute and template cannot be used together. Now, we are not specifying a template, but a class that does not have the specified attribute: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-9.8 ConfigurationError: The provided class doesn't have the specified attribute Cleanup ------- >>> import shutil >>> shutil.rmtree(temp_dir) ======= CHANGES ======= 3.7.2 (2010-05-25) ------------------ - Fixed unit tests broken under Python 2.4 by the switch to the standard library ``doctest`` module. 3.7.1 (2010-04-30) ------------------ - Removed use of 'zope.testing.doctest' in favor of stdlib's 'doctest. - Fixed dubious quoting in metadirectives.py. Closes https://bugs.launchpad.net/zope2/+bug/143774. 3.7.0 (2009-12-22) ------------------ - Depend on zope.browserpage in favor of zope.app.pagetemplate. 3.6.1 (2009-08-29) ------------------ - Fixed unit tests in README.txt. 3.6.0 (2009-08-02) ------------------ - Optimize the the script tag for the JS viewlet. This makes YSlow happy. - Remove ZCML slugs and old zpkg-related files. - Drop all testing dependncies except ``zope.testing``. 3.5.0 (2009-01-26) ------------------ - Removed the dependency on `zope.app.publisher` by moving four simple helper functions into this package and making the interface for describing the ZCML content provider directive explicit. - Typo fix in CSSViewlet docstring. 3.4.2 (2008-01-24) ------------------ - Re-release of 3.4.1 because of brown bag release. 3.4.1 (2008-01-21) ------------------ - bugfix, implemented missing __contains__ method in IViewletManager - implemented additional viewlet managers offering weight ordered sorting - implemented additional viewlet managers offering conditional filtering 3.4.1a (2007-4-22) ------------------ - bugfix, added a missing ',' behind zope.i18nmessageid. - recreated the README.txt removing everything except for the overview. 3.4.0 (2007-10-10) ------------------ - Initial release independent of the main Zope tree. Keywords: zope web html ui viewlet pattern Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Zope Public License Classifier: Programming Language :: Python Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Topic :: Internet :: WWW/HTTP Classifier: Framework :: Zope3 zope.viewlet-3.7.2/bootstrap.py0000644000175000017500000000742211376754171016472 0ustar tseavertseaver############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. $Id: bootstrap.py 111805 2010-04-30 22:21:55Z hannosch $ """ import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs) zope.viewlet-3.7.2/setup.py0000644000175000017500000000571111376754171015614 0ustar tseavertseaver############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## # This package is developed by the Zope Toolkit project, documented here: # http://docs.zope.org/zopetoolkit # When developing and releasing this package, please follow the documented # Zope Toolkit policies as described by this documentation. ############################################################################## """Setup for zope.viewlet package $Id: setup.py 112690 2010-05-25 14:02:00Z tseaver $ """ import os from setuptools import setup, find_packages def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() setup(name='zope.viewlet', version = '3.7.2', author='Zope Foundation and Contributors', author_email='zope-dev@zope.org', description='Zope Viewlets', long_description=( read('README.txt') + '\n\n' + 'Detailed Documentation\n' + '**********************\n\n' + '\n\n' + read('src', 'zope', 'viewlet', 'README.txt') + '\n\n' + read('src', 'zope', 'viewlet', 'directives.txt') + '\n\n' + read('CHANGES.txt') ), keywords = "zope web html ui viewlet pattern", classifiers = [ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Zope Public License', 'Programming Language :: Python', 'Natural Language :: English', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW/HTTP', 'Framework :: Zope3'], url='http://pypi.python.org/pypi/zope.viewlet', license='ZPL 2.1', packages=find_packages('src'), package_dir = {'': 'src'}, namespace_packages=['zope'], extras_require = dict( test=[ 'zope.testing', 'zope.size', ]), install_requires=[ 'setuptools', 'zope.browserpage>=3.10.1', 'zope.component', 'zope.configuration', 'zope.contentprovider', 'zope.event', 'zope.i18nmessageid', 'zope.interface', 'zope.location', 'zope.publisher', 'zope.schema', 'zope.security', 'zope.traversing', ], include_package_data = True, zip_safe = False, ) zope.viewlet-3.7.2/src/0000755000175000017500000000000011376754277014674 5ustar tseavertseaverzope.viewlet-3.7.2/src/zope.viewlet.egg-info/0000755000175000017500000000000011376754277021021 5ustar tseavertseaverzope.viewlet-3.7.2/src/zope.viewlet.egg-info/SOURCES.txt0000644000175000017500000000163111376754277022706 0ustar tseavertseaverCHANGES.txt COPYRIGHT.txt LICENSE.txt README.txt bootstrap.py buildout.cfg setup.py src/zope/__init__.py src/zope.viewlet.egg-info/PKG-INFO src/zope.viewlet.egg-info/SOURCES.txt src/zope.viewlet.egg-info/dependency_links.txt src/zope.viewlet.egg-info/namespace_packages.txt src/zope.viewlet.egg-info/not-zip-safe src/zope.viewlet.egg-info/requires.txt src/zope.viewlet.egg-info/top_level.txt src/zope/viewlet/README.txt src/zope/viewlet/__init__.py src/zope/viewlet/communicating-viewlets.txt src/zope/viewlet/configure.zcml src/zope/viewlet/css_bundle_viewlet.pt src/zope/viewlet/css_viewlet.pt src/zope/viewlet/directives.txt src/zope/viewlet/interfaces.py src/zope/viewlet/javascript_bundle_viewlet.pt src/zope/viewlet/javascript_viewlet.pt src/zope/viewlet/manager.py src/zope/viewlet/meta.zcml src/zope/viewlet/metaconfigure.py src/zope/viewlet/metadirectives.py src/zope/viewlet/tests.py src/zope/viewlet/viewlet.pyzope.viewlet-3.7.2/src/zope.viewlet.egg-info/dependency_links.txt0000644000175000017500000000000111376754276025066 0ustar tseavertseaver zope.viewlet-3.7.2/src/zope.viewlet.egg-info/top_level.txt0000644000175000017500000000000511376754276023545 0ustar tseavertseaverzope zope.viewlet-3.7.2/src/zope.viewlet.egg-info/namespace_packages.txt0000644000175000017500000000000511376754276025346 0ustar tseavertseaverzope zope.viewlet-3.7.2/src/zope.viewlet.egg-info/requires.txt0000644000175000017500000000035511376754276023423 0ustar tseavertseaversetuptools zope.browserpage>=3.10.1 zope.component zope.configuration zope.contentprovider zope.event zope.i18nmessageid zope.interface zope.location zope.publisher zope.schema zope.security zope.traversing [test] zope.testing zope.sizezope.viewlet-3.7.2/src/zope.viewlet.egg-info/PKG-INFO0000644000175000017500000017667211376754276022140 0ustar tseavertseaverMetadata-Version: 1.0 Name: zope.viewlet Version: 3.7.2 Summary: Zope Viewlets Home-page: http://pypi.python.org/pypi/zope.viewlet Author: Zope Foundation and Contributors Author-email: zope-dev@zope.org License: ZPL 2.1 Description: Viewlets provide a generic framework for building pluggable user interfaces. Detailed Documentation ********************** ============================= Viewlets and Viewlet Managers ============================= Let's start with some motivation. Using content providers allows us to insert one piece of HTML content. In most Web development, however, you are often interested in defining some sort of region and then allow developers to register content for those regions. >>> from zope.viewlet import interfaces Design Notes ------------ As mentioned above, besides inserting snippets of HTML at places, we more frequently want to define a region in our page and allow specialized content providers to be inserted based on configuration. Those specialized content providers are known as viewlets and are only available inside viewlet managers, which are just a more complex example of content providers. Unfortunately, the Java world does not implement this layer separately. The viewlet manager is most similar to a Java "channel", but we decided against using this name, since it is very generic and not very meaningful. The viewlet has no Java counterpart, since Java does not implement content providers using a component architecture and thus does not register content providers specifically for viewlet managers, which I believe makes the Java implementation less useful as a generic concept. In fact, the main design goal in the Java world is the implementation of reusable and sharable portlets. The scope for Zope 3 is larger, since we want to provide a generic framework for building pluggable user interfaces. The Viewlet Manager ------------------- In this implementation of viewlets, those regions are just content providers called viewlet managers that manage a special type of content providers known as viewlets. Every viewlet manager handles the viewlets registered for it: >>> class ILeftColumn(interfaces.IViewletManager): ... """Viewlet manager located in the left column.""" You can then create a viewlet manager using this interface now: >>> from zope.viewlet import manager >>> LeftColumn = manager.ViewletManager('left', ILeftColumn) Now we have to instantiate it: >>> import zope.interface >>> class Content(object): ... zope.interface.implements(zope.interface.Interface) >>> content = Content() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> from zope.publisher.interfaces.browser import IBrowserView >>> class View(object): ... zope.interface.implements(IBrowserView) ... def __init__(self, context, request): ... pass >>> view = View(content, request) >>> leftColumn = LeftColumn(content, request, view) So initially nothing gets rendered: >>> leftColumn.update() >>> leftColumn.render() u'' But now we register some viewlets for the manager >>> import zope.component >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> class WeatherBox(object): ... zope.interface.implements(interfaces.IViewlet) ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... ... def update(self): ... pass ... ... def render(self): ... return u'
It is sunny today!
' >>> # Create a security checker for viewlets. >>> from zope.security.checker import NamesChecker, defineChecker >>> viewletChecker = NamesChecker(('update', 'render')) >>> defineChecker(WeatherBox, viewletChecker) >>> zope.component.provideAdapter( ... WeatherBox, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, ILeftColumn), ... interfaces.IViewlet, name='weather') >>> from zope.location.interfaces import ILocation >>> class SportBox(object): ... zope.interface.implements(interfaces.IViewlet, ... ILocation) ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... ... def update(self): ... pass ... ... def render(self): ... return u'
Patriots (23) : Steelers (7)
' >>> defineChecker(SportBox, viewletChecker) >>> zope.component.provideAdapter( ... SportBox, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, ILeftColumn), ... interfaces.IViewlet, name='sport') and thus the left column is filled. Note that also events get fired before viewlets are updated. We register a simple handler to demonstrate this behaviour. >>> from zope.contentprovider.interfaces import IBeforeUpdateEvent >>> events = [] >>> def handler(ev): ... events.append(ev) >>> zope.component.provideHandler(handler, (IBeforeUpdateEvent,)) >>> leftColumn.update() >>> [(ev, ev.object.__class__.__name__) for ev in events] [(, 'SportBox'), (, 'WeatherBox')] >>> print leftColumn.render()
Patriots (23) : Steelers (7)
It is sunny today!
But this is of course pretty lame, since there is no way of specifying how the viewlets are put together. But we have a solution. The second argument of the ``ViewletManager()`` function is a template in which we can specify how the viewlets are put together: >>> import os, tempfile >>> temp_dir = tempfile.mkdtemp() >>> leftColTemplate = os.path.join(temp_dir, 'leftCol.pt') >>> open(leftColTemplate, 'w').write(''' ...
... ...
... ''') >>> LeftColumn = manager.ViewletManager('left', ILeftColumn, ... template=leftColTemplate) >>> leftColumn = LeftColumn(content, request, view) TODO: Fix this silly thing; viewlets should be directly available. As you can see, the viewlet manager provides a global ``options/viewlets`` variable that is an iterable of all the available viewlets in the correct order: >>> leftColumn.update() >>> print leftColumn.render().strip()
Patriots (23) : Steelers (7)
It is sunny today!
If a viewlet provides ILocation the ``__name__`` attribute of the viewlet is set to the name under which the viewlet is registered. >>> [getattr(viewlet, '__name__', None) for viewlet in leftColumn.viewlets] [u'sport', None] You can also lookup the viewlets directly for management purposes: >>> leftColumn['weather'] >>> leftColumn.get('weather') The viewlet manager also provides the __contains__ method defined in IReadMapping: >>> 'weather' in leftColumn True >>> 'unknown' in leftColumn False If the viewlet is not found, then the expected behavior is provided: >>> leftColumn['stock'] Traceback (most recent call last): ... ComponentLookupError: No provider with name `stock` found. >>> leftColumn.get('stock') is None True Customizing the default Viewlet Manager --------------------------------------- One important feature of any viewlet manager is to be able to filter and sort the viewlets it is displaying. The default viewlet manager that we have been using in the tests above, supports filtering by access availability and sorting via the viewlet's ``__cmp__()`` method (default). You can easily override this default policy by providing a base viewlet manager class. In our case we will manage the viewlets using a global list: >>> shown = ['weather', 'sport'] The viewlet manager base class now uses this list: >>> class ListViewletManager(object): ... ... def filter(self, viewlets): ... viewlets = super(ListViewletManager, self).filter(viewlets) ... return [(name, viewlet) ... for name, viewlet in viewlets ... if name in shown] ... ... def sort(self, viewlets): ... viewlets = dict(viewlets) ... return [(name, viewlets[name]) for name in shown] Let's now create a new viewlet manager: >>> LeftColumn = manager.ViewletManager( ... 'left', ILeftColumn, bases=(ListViewletManager,), ... template=leftColTemplate) >>> leftColumn = LeftColumn(content, request, view) So we get the weather box first and the sport box second: >>> leftColumn.update() >>> print leftColumn.render().strip()
It is sunny today!
Patriots (23) : Steelers (7)
Now let's change the order... >>> shown.reverse() and the order should switch as well: >>> leftColumn.update() >>> print leftColumn.render().strip()
Patriots (23) : Steelers (7)
It is sunny today!
Of course, we also can remove a shown viewlet: >>> weather = shown.pop() >>> leftColumn.update() >>> print leftColumn.render().strip()
Patriots (23) : Steelers (7)
WeightOrderedViewletManager --------------------------- The weight ordered viewlet manager offers ordering viewlets by a additional weight argument. Viewlets which doesn't provide a weight attribute will get a weight of 0 (zero). Let's define a new column: >>> class IWeightedColumn(interfaces.IViewletManager): ... """Column with weighted viewlet manager.""" First register a template for the weight ordered viewlet manager: >>> weightedColTemplate = os.path.join(temp_dir, 'weightedColTemplate.pt') >>> open(weightedColTemplate, 'w').write(''' ...
... ...
... ''') And create a new weight ordered viewlet manager: >>> from zope.viewlet.manager import WeightOrderedViewletManager >>> WeightedColumn = manager.ViewletManager( ... 'left', IWeightedColumn, bases=(WeightOrderedViewletManager,), ... template=weightedColTemplate) >>> weightedColumn = WeightedColumn(content, request, view) Let's create some viewlets: >>> from zope.viewlet import viewlet >>> class FirstViewlet(viewlet.ViewletBase): ... ... weight = 1 ... ... def render(self): ... return u'
first
' >>> class SecondViewlet(viewlet.ViewletBase): ... ... weight = 2 ... ... def render(self): ... return u'
second
' >>> class ThirdViewlet(viewlet.ViewletBase): ... ... weight = 3 ... ... def render(self): ... return u'
third
' >>> class UnWeightedViewlet(viewlet.ViewletBase): ... ... def render(self): ... return u'
unweighted
' >>> defineChecker(FirstViewlet, viewletChecker) >>> defineChecker(SecondViewlet, viewletChecker) >>> defineChecker(ThirdViewlet, viewletChecker) >>> defineChecker(UnWeightedViewlet, viewletChecker) >>> zope.component.provideAdapter( ... ThirdViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='third') >>> zope.component.provideAdapter( ... FirstViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='first') >>> zope.component.provideAdapter( ... SecondViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='second') >>> zope.component.provideAdapter( ... UnWeightedViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='unweighted') And check the order: >>> weightedColumn.update() >>> print weightedColumn.render().strip()
unweighted
first
second
third
ConditionalViewletManager ------------------------- The conditional ordered viewlet manager offers ordering viewlets by a additional weight argument and filters by the available attribute if a supported by the viewlet. Viewlets which doesn't provide a available attribute will not get skipped. The default weight value for viewlets which doesn't provide a weight attribute is 0 (zero). Let's define a new column: >>> class IConditionalColumn(interfaces.IViewletManager): ... """Column with weighted viewlet manager.""" First register a template for the weight ordered viewlet manager: >>> conditionalColTemplate = os.path.join(temp_dir, ... 'conditionalColTemplate.pt') >>> open(conditionalColTemplate, 'w').write(''' ...
... ...
... ''') And create a new conditional viewlet manager: >>> from zope.viewlet.manager import ConditionalViewletManager >>> ConditionalColumn = manager.ViewletManager( ... 'left', IConditionalColumn, bases=(ConditionalViewletManager,), ... template=conditionalColTemplate) >>> conditionalColumn = ConditionalColumn(content, request, view) Let's create some viewlets. We also use the previous viewlets supporting no weight and or no available attribute: >>> from zope.viewlet import viewlet >>> class AvailableViewlet(viewlet.ViewletBase): ... ... weight = 4 ... ... available = True ... ... def render(self): ... return u'
available
' >>> class UnAvailableViewlet(viewlet.ViewletBase): ... ... weight = 5 ... ... available = False ... ... def render(self): ... return u'
not available
' >>> defineChecker(AvailableViewlet, viewletChecker) >>> defineChecker(UnAvailableViewlet, viewletChecker) >>> zope.component.provideAdapter( ... ThirdViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='third') >>> zope.component.provideAdapter( ... FirstViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='first') >>> zope.component.provideAdapter( ... SecondViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='second') >>> zope.component.provideAdapter( ... UnWeightedViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='unweighted') >>> zope.component.provideAdapter( ... AvailableViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='available') >>> zope.component.provideAdapter( ... UnAvailableViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='unavailable') And check the order: >>> conditionalColumn.update() >>> print conditionalColumn.render().strip()
unweighted
first
second
third
available
Viewlet Base Classes -------------------- To make the creation of viewlets simpler, a set of useful base classes and helper functions are provided. The first class is a base class that simply defines the constructor: >>> base = viewlet.ViewletBase('context', 'request', 'view', 'manager') >>> base.context 'context' >>> base.request 'request' >>> base.__parent__ 'view' >>> base.manager 'manager' But a default ``render()`` method implementation is not provided: >>> base.render() Traceback (most recent call last): ... NotImplementedError: `render` method must be implemented by subclass. If you have already an existing class that produces the HTML content in some method, then the ``SimpleAttributeViewlet`` might be for you, since it can be used to convert any class quickly into a viewlet: >>> class FooViewlet(viewlet.SimpleAttributeViewlet): ... __page_attribute__ = 'foo' ... ... def foo(self): ... return 'output' The `__page_attribute__` attribute provides the name of the function to call for rendering. >>> foo = FooViewlet('context', 'request', 'view', 'manager') >>> foo.foo() 'output' >>> foo.render() 'output' If you specify `render` as the attribute an error is raised to prevent infinite recursion: >>> foo.__page_attribute__ = 'render' >>> foo.render() Traceback (most recent call last): ... AttributeError: render The same is true if the specified attribute does not exist: >>> foo.__page_attribute__ = 'bar' >>> foo.render() Traceback (most recent call last): ... AttributeError: 'FooViewlet' object has no attribute 'bar' To create simple template-based viewlets you can use the ``SimpleViewletClass()`` function. This function is very similar to its view equivalent and is used by the ZCML directives to create viewlets. The result of this function call will be a fully functional viewlet class. Let's start by simply specifying a template only: >>> template = os.path.join(temp_dir, 'demoTemplate.pt') >>> open(template, 'w').write('''
contents
''') >>> Demo = viewlet.SimpleViewletClass(template) >>> print Demo(content, request, view, manager).render()
contents
Now let's additionally specify a class that can provide additional features: >>> class MyViewlet(object): ... myAttribute = 8 >>> Demo = viewlet.SimpleViewletClass(template, bases=(MyViewlet,)) >>> MyViewlet in Demo.__bases__ True >>> Demo(content, request, view, manager).myAttribute 8 The final important feature is the ability to pass in further attributes to the class: >>> Demo = viewlet.SimpleViewletClass( ... template, attributes={'here': 'now', 'lucky': 3}) >>> demo = Demo(content, request, view, manager) >>> demo.here 'now' >>> demo.lucky 3 As for all views, they must provide a name that can also be passed to the function: >>> Demo = viewlet.SimpleViewletClass(template, name='demoViewlet') >>> demo = Demo(content, request, view, manager) >>> demo.__name__ 'demoViewlet' In addition to the the generic viewlet code above, the package comes with two viewlet base classes and helper functions for inserting CSS and Javascript links into HTML headers, since those two are so very common. I am only going to demonstrate the helper functions here, since those demonstrations will fully demonstrate the functionality of the base classes as well. The viewlet will look up the resource it was given and tries to produce the absolute URL for it: >>> class JSResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/resource.js' >>> zope.component.provideAdapter( ... JSResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='resource.js') >>> JSViewlet = viewlet.JavaScriptViewlet('resource.js') >>> print JSViewlet(content, request, view, manager).render().strip() There is also a javascript viewlet base class which knows how to render more then one javascript resource file: >>> class JSSecondResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/second-resource.js' >>> zope.component.provideAdapter( ... JSSecondResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='second-resource.js') >>> JSBundleViewlet = viewlet.JavaScriptBundleViewlet(('resource.js', ... 'second-resource.js')) >>> print JSBundleViewlet(content, request, view, manager).render().strip() The same works for the CSS resource viewlet: >>> class CSSResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/resource.css' >>> zope.component.provideAdapter( ... CSSResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='resource.css') >>> CSSViewlet = viewlet.CSSViewlet('resource.css') >>> print CSSViewlet(content, request, view, manager).render().strip() You can also change the media type and the rel attribute: >>> CSSViewlet = viewlet.CSSViewlet('resource.css', media='print', rel='css') >>> print CSSViewlet(content, request, view, manager).render().strip() There is also a bundle viewlet for CSS links: >>> class CSSPrintResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/print-resource.css' >>> zope.component.provideAdapter( ... CSSPrintResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='print-resource.css') >>> items = [] >>> items.append({'path':'resource.css', 'rel':'stylesheet', 'media':'all'}) >>> items.append({'path':'print-resource.css', 'media':'print'}) >>> CSSBundleViewlet = viewlet.CSSBundleViewlet(items) >>> print CSSBundleViewlet(content, request, view, manager).render().strip() A Complex Example ----------------- The Data ~~~~~~~~ So far we have only demonstrated simple (maybe overly trivial) use cases of the viewlet system. In the following example, we are going to develop a generic contents view for files. The step is to create a file component: >>> class IFile(zope.interface.Interface): ... data = zope.interface.Attribute('Data of file.') >>> class File(object): ... zope.interface.implements(IFile) ... def __init__(self, data=''): ... self.__name__ = '' ... self.data = data Since we want to also provide the size of a file, here a simple implementation of the ``ISized`` interface: >>> from zope import size >>> class FileSized(object): ... zope.interface.implements(size.interfaces.ISized) ... zope.component.adapts(IFile) ... ... def __init__(self, file): ... self.file = file ... ... def sizeForSorting(self): ... return 'byte', len(self.file.data) ... ... def sizeForDisplay(self): ... return '%i bytes' %len(self.file.data) >>> zope.component.provideAdapter(FileSized) We also need a container to which we can add files: >>> class Container(dict): ... def __setitem__(self, name, value): ... value.__name__ = name ... super(Container, self).__setitem__(name, value) Here is some sample data: >>> container = Container() >>> container['test.txt'] = File('Hello World!') >>> container['mypage.html'] = File('Hello World!') >>> container['data.xml'] = File('Hello World!') The View ~~~~~~~~ The contents view of the container should iterate through the container and represent the files in a table: >>> contentsTemplate = os.path.join(temp_dir, 'contents.pt') >>> open(contentsTemplate, 'w').write(''' ... ... ...

Contents

...
... ... ... ''') >>> from zope.browserpage.simpleviewclass import SimpleViewClass >>> Contents = SimpleViewClass(contentsTemplate, name='contents.html') The Viewlet Manager ~~~~~~~~~~~~~~~~~~~ Now we have to write our own viewlet manager. In this case we cannot use the default implementation, since the viewlets will be looked up for each different item: >>> shownColumns = [] >>> class ContentsViewletManager(object): ... zope.interface.implements(interfaces.IViewletManager) ... index = None ... ... def __init__(self, context, request, view): ... self.context = context ... self.request = request ... self.__parent__ = view ... ... def update(self): ... rows = [] ... for name, value in self.context.items(): ... rows.append( ... [zope.component.getMultiAdapter( ... (value, self.request, self.__parent__, self), ... interfaces.IViewlet, name=colname) ... for colname in shownColumns]) ... [entry.update() for entry in rows[-1]] ... self.rows = rows ... ... def render(self, *args, **kw): ... return self.index(*args, **kw) Now we need a template to produce the contents table: >>> tableTemplate = os.path.join(temp_dir, 'table.pt') >>> open(tableTemplate, 'w').write(''' ... ... ... ... ...
... ...
... ''') From the two pieces above, we can generate the final viewlet manager class and register it (it's a bit tedious, I know): >>> from zope.browserpage import ViewPageTemplateFile >>> ContentsViewletManager = type( ... 'ContentsViewletManager', (ContentsViewletManager,), ... {'index': ViewPageTemplateFile(tableTemplate)}) >>> zope.component.provideAdapter( ... ContentsViewletManager, ... (Container, IDefaultBrowserLayer, zope.interface.Interface), ... interfaces.IViewletManager, name='contents') Since we have not defined any viewlets yet, the table is totally empty: >>> contents = Contents(container, request) >>> print contents().strip()

Contents

The Viewlets and the Final Result ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Now let's create a first viewlet for the manager... >>> class NameViewlet(object): ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... self.context = context ... ... def update(self): ... pass ... ... def render(self): ... return self.context.__name__ and register it: >>> zope.component.provideAdapter( ... NameViewlet, ... (IFile, IDefaultBrowserLayer, ... zope.interface.Interface, interfaces.IViewletManager), ... interfaces.IViewlet, name='name') Note how you register the viewlet on ``IFile`` and not on the container. Now we should be able to see the name for each file in the container: >>> print contents().strip()

Contents

Waaa, nothing there! What happened? Well, we have to tell our user preferences that we want to see the name as a column in the table: >>> shownColumns = ['name'] >>> print contents().strip()

Contents

mypage.html
data.xml
test.txt
Let's now write a second viewlet that will display the size of the object for us: >>> class SizeViewlet(object): ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... self.context = context ... ... def update(self): ... pass ... ... def render(self): ... return size.interfaces.ISized(self.context).sizeForDisplay() >>> zope.component.provideAdapter( ... SizeViewlet, ... (IFile, IDefaultBrowserLayer, ... zope.interface.Interface, interfaces.IViewletManager), ... interfaces.IViewlet, name='size') After we added it to the list of shown columns, >>> shownColumns = ['name', 'size'] we can see an entry for it: >>> print contents().strip()

Contents

mypage.html 38 bytes
data.xml 31 bytes
test.txt 12 bytes
If we switch the two columns around, >>> shownColumns = ['size', 'name'] the result will be >>> print contents().strip()

Contents

38 bytes mypage.html
31 bytes data.xml
12 bytes test.txt
Supporting Sorting ~~~~~~~~~~~~~~~~~~ Oftentimes you also want to batch and sort the entries in a table. Since those two features are not part of the view logic, they should be treated with independent components. In this example, we are going to only implement sorting using a simple utility: >>> class ISorter(zope.interface.Interface): ... ... def sort(values): ... """Sort the values.""" >>> class SortByName(object): ... zope.interface.implements(ISorter) ... ... def sort(self, values): ... return sorted(values, lambda x, y: cmp(x.__name__, y.__name__)) >>> zope.component.provideUtility(SortByName(), name='name') >>> class SortBySize(object): ... zope.interface.implements(ISorter) ... ... def sort(self, values): ... return sorted( ... values, ... lambda x, y: cmp(size.interfaces.ISized(x).sizeForSorting(), ... size.interfaces.ISized(y).sizeForSorting())) >>> zope.component.provideUtility(SortBySize(), name='size') Note that we decided to give the sorter utilities the same name as the corresponding viewlet. This convention will make our implementation of the viewlet manager much simpler: >>> sortByColumn = '' >>> class SortedContentsViewletManager(object): ... zope.interface.implements(interfaces.IViewletManager) ... index = None ... ... def __init__(self, context, request, view): ... self.context = context ... self.request = request ... self.__parent__ = view ... ... def update(self): ... values = self.context.values() ... ... if sortByColumn: ... sorter = zope.component.queryUtility(ISorter, sortByColumn) ... if sorter: ... values = sorter.sort(values) ... ... rows = [] ... for value in values: ... rows.append( ... [zope.component.getMultiAdapter( ... (value, self.request, self.__parent__, self), ... interfaces.IViewlet, name=colname) ... for colname in shownColumns]) ... [entry.update() for entry in rows[-1]] ... self.rows = rows ... ... def render(self, *args, **kw): ... return self.index(*args, **kw) As you can see, the concern of sorting is cleanly separated from generating the view code. In MVC terms that means that the controller (sort) is logically separated from the view (viewlets). Let's now do the registration dance for the new viewlet manager. We simply override the existing registration: >>> SortedContentsViewletManager = type( ... 'SortedContentsViewletManager', (SortedContentsViewletManager,), ... {'index': ViewPageTemplateFile(tableTemplate)}) >>> zope.component.provideAdapter( ... SortedContentsViewletManager, ... (Container, IDefaultBrowserLayer, zope.interface.Interface), ... interfaces.IViewletManager, name='contents') Finally we sort the contents by name: >>> shownColumns = ['name', 'size'] >>> sortByColumn = 'name' >>> print contents().strip()

Contents

data.xml 31 bytes
mypage.html 38 bytes
test.txt 12 bytes
Now let's sort by size: >>> sortByColumn = 'size' >>> print contents().strip()

Contents

test.txt 12 bytes
data.xml 31 bytes
mypage.html 38 bytes
That's it! As you can see, in a few steps we have built a pretty flexible contents view with selectable columns and sorting. However, there is a lot of room for extending this example: - Table Header: The table header cell for each column should be a different type of viewlet, but registered under the same name. The column header viewlet also adapts the container not the item. The header column should also be able to control the sorting. - Batching: A simple implementation of batching should work very similar to the sorting feature. Of course, efficient implementations should somehow combine batching and sorting more effectively. - Sorting in ascending and descending order: Currently, you can only sort from the smallest to the highest value; however, this limitation is almost superficial and can easily be removed by making the sorters a bit more flexible. - Further Columns: For a real application, you would want to implement other columns, of course. You would also probably want some sort of fallback for the case that a viewlet is not found for a particular container item and column. Cleanup ------- >>> import shutil >>> shutil.rmtree(temp_dir) ================================ The ``viewletManager`` Directive ================================ The ``viewletManager`` directive allows you to quickly register a new viewlet manager without worrying about the details of the ``adapter`` directive. Before we can use the directives, we have to register their handlers by executing the package's meta configuration: >>> from zope.configuration import xmlconfig >>> context = xmlconfig.string(''' ... ... ... ... ''') Now we can register a viewlet manager: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Let's make sure the directive has really issued a sensible adapter registration; to do that, we create some dummy content, request and view objects: >>> import zope.interface >>> class Content(object): ... zope.interface.implements(zope.interface.Interface) >>> content = Content() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> from zope.publisher.browser import BrowserView >>> view = BrowserView(content, request) Now let's lookup the manager. This particular registration is pretty boring: >>> import zope.component >>> from zope.viewlet import interfaces >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ... interfaces.IViewletManager, name='defaultmanager') >>> manager object ...> >>> interfaces.IViewletManager.providedBy(manager) True >>> manager.template is None True >>> manager.update() >>> manager.render() u'' However, this registration is not very useful, since we did specify a specific viewlet manager interface, a specific content interface, specific view or specific layer. This means that all viewlets registered will be found. The first step to effectively using the viewlet manager directive is to define a special viewlet manager interface: >>> class ILeftColumn(interfaces.IViewletManager): ... """Left column of my page.""" Now we can register register a manager providing this interface: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager object ...> >>> ILeftColumn.providedBy(manager) True >>> manager.template is None True >>> manager.update() >>> manager.render() u'' Next let's see what happens, if we specify a template for the viewlet manager: >>> import os, tempfile >>> temp_dir = tempfile.mkdtemp() >>> leftColumnTemplate = os.path.join(temp_dir, 'leftcolumn.pt') >>> open(leftColumnTemplate, 'w').write(''' ...
...
...
... ''') >>> context = xmlconfig.string(''' ... ... ... ... ''' %leftColumnTemplate, context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager object ...> >>> ILeftColumn.providedBy(manager) True >>> manager.template ...>> >>> manager.update() >>> print manager.render().strip()
Additionally you can specify a class that will serve as a base to the default viewlet manager or be a viewlet manager in its own right. In our case we will provide a custom implementation of the ``sort()`` method, which will sort by a weight attribute in the viewlet: >>> class WeightBasedSorting(object): ... def sort(self, viewlets): ... return sorted(viewlets, ... lambda x, y: cmp(x[1].weight, y[1].weight)) >>> context = xmlconfig.string(''' ... ... ... ... ''' %leftColumnTemplate, context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager object ...> >>> manager.__class__.__bases__ (, ) >>> ILeftColumn.providedBy(manager) True >>> manager.template ...>> >>> manager.update() >>> print manager.render().strip()
Finally, if a non-existent template is specified, an error is raised: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-7.8 ConfigurationError: ('No such file', '...foo.pt') ========================= The ``viewlet`` Directive ========================= Now that we have a viewlet manager, we have to register some viewlets for it. The ``viewlet`` directive is similar to the ``viewletManager`` directive, except that the viewlet is also registered for a particular manager interface, as seen below: >>> weatherTemplate = os.path.join(temp_dir, 'weather.pt') >>> open(weatherTemplate, 'w').write(''' ...
sunny
... ''') >>> context = xmlconfig.string(''' ... ... ... ... ''' % weatherTemplate, context=context) If we look into the adapter registry, we will find the viewlet: >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='weather') >>> viewlet.render().strip() u'
sunny
' >>> viewlet.extra_string_attributes u'can be specified' The manager now also gives us the output of the one and only viewlet: >>> manager.update() >>> print manager.render().strip()
sunny
Let's now ensure that we can also specify a viewlet class: >>> class Weather(object): ... weight = 0 >>> context = xmlconfig.string(''' ... ... ... ... ''' % weatherTemplate, context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='weather2') >>> viewlet().strip() u'
sunny
' Okay, so the template-driven cases work. But just specifying a class should also work: >>> class Sport(object): ... weight = 0 ... def __call__(self): ... return u'Red Sox vs. White Sox' >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, name='sport') >>> viewlet() u'Red Sox vs. White Sox' It should also be possible to specify an alternative attribute of the class to be rendered upon calling the viewlet: >>> class Stock(object): ... weight = 0 ... def getStockTicker(self): ... return u'SRC $5.19' >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='stock') >>> viewlet.render() u'SRC $5.19' A final feature the ``viewlet`` directive is that it supports the specification of any number of keyword arguments: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='stock2') >>> viewlet.weight u'8' Error Scenarios --------------- Neither the class or template have been specified: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-7.8 ConfigurationError: Must specify a class or template The specified attribute is not ``__call__``, but also a template has been specified: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-9.8 ConfigurationError: Attribute and template cannot be used together. Now, we are not specifying a template, but a class that does not have the specified attribute: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-9.8 ConfigurationError: The provided class doesn't have the specified attribute Cleanup ------- >>> import shutil >>> shutil.rmtree(temp_dir) ======= CHANGES ======= 3.7.2 (2010-05-25) ------------------ - Fixed unit tests broken under Python 2.4 by the switch to the standard library ``doctest`` module. 3.7.1 (2010-04-30) ------------------ - Removed use of 'zope.testing.doctest' in favor of stdlib's 'doctest. - Fixed dubious quoting in metadirectives.py. Closes https://bugs.launchpad.net/zope2/+bug/143774. 3.7.0 (2009-12-22) ------------------ - Depend on zope.browserpage in favor of zope.app.pagetemplate. 3.6.1 (2009-08-29) ------------------ - Fixed unit tests in README.txt. 3.6.0 (2009-08-02) ------------------ - Optimize the the script tag for the JS viewlet. This makes YSlow happy. - Remove ZCML slugs and old zpkg-related files. - Drop all testing dependncies except ``zope.testing``. 3.5.0 (2009-01-26) ------------------ - Removed the dependency on `zope.app.publisher` by moving four simple helper functions into this package and making the interface for describing the ZCML content provider directive explicit. - Typo fix in CSSViewlet docstring. 3.4.2 (2008-01-24) ------------------ - Re-release of 3.4.1 because of brown bag release. 3.4.1 (2008-01-21) ------------------ - bugfix, implemented missing __contains__ method in IViewletManager - implemented additional viewlet managers offering weight ordered sorting - implemented additional viewlet managers offering conditional filtering 3.4.1a (2007-4-22) ------------------ - bugfix, added a missing ',' behind zope.i18nmessageid. - recreated the README.txt removing everything except for the overview. 3.4.0 (2007-10-10) ------------------ - Initial release independent of the main Zope tree. Keywords: zope web html ui viewlet pattern Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: Zope Public License Classifier: Programming Language :: Python Classifier: Natural Language :: English Classifier: Operating System :: OS Independent Classifier: Topic :: Internet :: WWW/HTTP Classifier: Framework :: Zope3 zope.viewlet-3.7.2/src/zope.viewlet.egg-info/not-zip-safe0000644000175000017500000000000111376754212023234 0ustar tseavertseaver zope.viewlet-3.7.2/src/zope/0000755000175000017500000000000011376754277015651 5ustar tseavertseaverzope.viewlet-3.7.2/src/zope/viewlet/0000755000175000017500000000000011376754277017330 5ustar tseavertseaverzope.viewlet-3.7.2/src/zope/viewlet/manager.py0000644000175000017500000001460711376754171021315 0ustar tseavertseaver############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Content Provider Manager implementation $Id: manager.py 112059 2010-05-05 19:40:35Z tseaver $ """ __docformat__ = 'restructuredtext' import zope.component import zope.interface import zope.security import zope.event from zope.browserpage import ViewPageTemplateFile from zope.viewlet import interfaces from zope.location.interfaces import ILocation from zope.contentprovider.interfaces import BeforeUpdateEvent class ViewletManagerBase(object): """The Viewlet Manager Base A generic manager class which can be instantiated """ zope.interface.implements(interfaces.IViewletManager) template = None def __init__(self, context, request, view): self.__updated = False self.__parent__ = view self.context = context self.request = request def __getitem__(self, name): """See zope.interface.common.mapping.IReadMapping""" # Find the viewlet viewlet = zope.component.queryMultiAdapter( (self.context, self.request, self.__parent__, self), interfaces.IViewlet, name=name) # If the viewlet was not found, then raise a lookup error if viewlet is None: raise zope.component.interfaces.ComponentLookupError( 'No provider with name `%s` found.' %name) # If the viewlet cannot be accessed, then raise an # unauthorized error if not zope.security.canAccess(viewlet, 'render'): raise zope.security.interfaces.Unauthorized( 'You are not authorized to access the provider ' 'called `%s`.' %name) # Return the viewlet. return viewlet def get(self, name, default=None): """See zope.interface.common.mapping.IReadMapping""" try: return self[name] except (zope.component.interfaces.ComponentLookupError, zope.security.interfaces.Unauthorized): return default def __contains__(self, name): """See zope.interface.common.mapping.IReadMapping""" return bool(self.get(name, False)) def filter(self, viewlets): """Sort out all content providers ``viewlets`` is a list of tuples of the form (name, viewlet). """ # Only return viewlets accessible to the principal return [(name, viewlet) for name, viewlet in viewlets if zope.security.canAccess(viewlet, 'render')] def sort(self, viewlets): """Sort the viewlets. ``viewlets`` is a list of tuples of the form (name, viewlet). """ # By default, use the standard Python way of doing sorting. return sorted(viewlets, lambda x, y: cmp(x[1], y[1])) def update(self): """See zope.contentprovider.interfaces.IContentProvider""" self.__updated = True # Find all content providers for the region viewlets = zope.component.getAdapters( (self.context, self.request, self.__parent__, self), interfaces.IViewlet) viewlets = self.filter(viewlets) viewlets = self.sort(viewlets) # Just use the viewlets from now on self.viewlets=[] for name, viewlet in viewlets: if ILocation.providedBy(viewlet): viewlet.__name__ = name self.viewlets.append(viewlet) self._updateViewlets() def _updateViewlets(self): """Calls update on all viewlets and fires events""" for viewlet in self.viewlets: zope.event.notify(BeforeUpdateEvent(viewlet, self.request)) viewlet.update() def render(self): """See zope.contentprovider.interfaces.IContentProvider""" # Now render the view if self.template: return self.template(viewlets=self.viewlets) else: return u'\n'.join([viewlet.render() for viewlet in self.viewlets]) def ViewletManager(name, interface, template=None, bases=()): attrDict = {'__name__' : name} if template is not None: attrDict['template'] = ViewPageTemplateFile(template) if ViewletManagerBase not in bases: # Make sure that we do not get a default viewlet manager mixin, if the # provided base is already a full viewlet manager implementation. if not (len(bases) == 1 and interfaces.IViewletManager.implementedBy(bases[0])): bases = bases + (ViewletManagerBase,) ViewletManager = type( '' % interface.getName(), bases, attrDict) zope.interface.classImplements(ViewletManager, interface) return ViewletManager def getWeight((name, viewlet)): try: return int(viewlet.weight) except AttributeError: return 0 class WeightOrderedViewletManager(ViewletManagerBase): """Weight ordered viewlet managers.""" def sort(self, viewlets): return sorted(viewlets, key=getWeight) def render(self): """See zope.contentprovider.interfaces.IContentProvider""" # do not render a manager template if no viewlets are avaiable if not self.viewlets: return u'' elif self.template: return self.template(viewlets=self.viewlets) else: return u'\n'.join([viewlet.render() for viewlet in self.viewlets]) def isAvailable(viewlet): try: return zope.security.canAccess(viewlet, 'render') and viewlet.available except AttributeError: return True class ConditionalViewletManager(WeightOrderedViewletManager): """Conditional weight ordered viewlet managers.""" def filter(self, viewlets): """Sort out all viewlets which are explicit not available ``viewlets`` is a list of tuples of the form (name, viewlet). """ return [(name, viewlet) for name, viewlet in viewlets if isAvailable(viewlet)] zope.viewlet-3.7.2/src/zope/viewlet/css_bundle_viewlet.pt0000644000175000017500000000036511376754171023552 0ustar tseavertseaver zope.viewlet-3.7.2/src/zope/viewlet/communicating-viewlets.txt0000644000175000017500000000704011376754171024560 0ustar tseavertseaver============================================== A technique for communication between viewlets ============================================== Sometimes one wants viewlets to communicate with each other to supplement a more generic viewlet's behaviour with another viewlet. One example would be a viewlet that contains a search form created by a library such as z3c.form, plus a second viewlet that provides a list of search results. This is very simple to accomplish with zope.viewlet but has turned out not to be obvious, so here is an explicit example. It is not written as a doc test since it uses z3c.form which should not become a dependency of zope.viewlet. The viewlets ============ For the purpose of this example, we simulate a search form. Our search results are simply the characters of the search term and are stored on the viewlet as an attribute: class ISearchForm(zope.interface.Interface): searchterm = zope.schema.TextLine(title=u"Search term") class SearchForm(z3c.form.form.Form): ignoreContext = True fields = z3c.form.field.Fields(ISearchForm) results = "" @z3c.form.button.buttonAndHandler(u"Search") def search(self, action): data, errors = self.extractData() self.results = list(data["searchterm"]) (Notice that this example is minimized to point out communication between viewlets, and no care is taken to handle the form itself in the best way possible. In particular, one will probably want to make sure that the actual search is not performed more than once, which may happen with the above code.) The result list viewlet needs to display the results stored on the search form. Therefore, the result list viewlet needs to access that viewlet, which is probably the only tricky part (if there is any at all) in this example: Since viewlets know their viewlet manager which lets viewlets be looked up by ID, it is all a matter of the result list viewlet knowing the ID of the search form. We'll store the search form viewlet's ID as an attribute of the result list viewlet. Let's hard-code the ID for a start, then the result list looks like this: class ResultList(zope.viewlet.viewlet.ViewletBase): searchform_id = "searchform" def update(self): super(ResultList, self).update() searchform = self.manager[self.searchform_id] searchform.update() self.results = searchform.results def render(self): return "
    %s
" % "\n".join(u"
  • %s
  • " % x for x in self.results) Registering the viewlets ======================== As long as we treat the ID of the search form as hard-coded, we have to use the correct name when registering the two viewlets: Making the ID of the search form more flexible now doesn't even require changing any code: the viewlet directive may be passed arbitrary attributes which will be available as attributes of the ResultList objects. The attribute that holds our search form's ID is searchform_id, so we might register the viewlets like this: zope.viewlet-3.7.2/src/zope/viewlet/interfaces.py0000644000175000017500000000406411376754171022022 0ustar tseavertseaver############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Viewlet interfaces $Id: interfaces.py 112059 2010-05-05 19:40:35Z tseaver $ """ __docformat__ = 'restructuredtext' import zope.interface from zope.contentprovider.interfaces import IContentProvider from zope.i18nmessageid import MessageFactory _ = MessageFactory('zope') class IViewlet(IContentProvider): """A content provider that is managed by another content provider, known as viewlet manager. Note that you *cannot* call viewlets directly as a provider, i.e. through the TALES ``provider`` expression, since it always has to know its manager. """ manager = zope.interface.Attribute( """The Viewlet Manager The viewlet manager for which the viewlet is registered. The viewlet manager will contain any additional data that was provided by the view, for example the TAL namespace attributes. """) class IViewletManager(IContentProvider, zope.interface.common.mapping.IReadMapping): """A component that provides access to the content providers. The viewlet manager's resposibilities are: (1) Aggregation of all viewlets registered for the manager. (2) Apply a set of filters to determine the availability of the viewlets. (3) Sort the viewlets based on some implemented policy. (4) Provide an environment in which the viewlets are rendered. (5) Render itself containing the HTML content of the viewlets. """ zope.viewlet-3.7.2/src/zope/viewlet/meta.zcml0000644000175000017500000000076211376754171021143 0ustar tseavertseaver zope.viewlet-3.7.2/src/zope/viewlet/metaconfigure.py0000644000175000017500000002044411376754171022527 0ustar tseavertseaver############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Viewlet metadconfigure $Id: metaconfigure.py 112059 2010-05-05 19:40:35Z tseaver $ """ __docformat__ = 'restructuredtext' import os from zope.security import checker from zope.configuration.exceptions import ConfigurationError from zope.interface import Interface, classImplements from zope.publisher.interfaces.browser import IDefaultBrowserLayer from zope.publisher.interfaces.browser import IBrowserPublisher from zope.publisher.interfaces.browser import IBrowserView from zope.component import zcml from zope.component.interface import provideInterface from zope.viewlet import viewlet, manager, interfaces def viewletManagerDirective( _context, name, permission, for_=Interface, layer=IDefaultBrowserLayer, view=IBrowserView, provides=interfaces.IViewletManager, class_=None, template=None, allowed_interface=None, allowed_attributes=None): # A list of attributes available under the provided permission required = {} # Get the permission; mainly to correctly handle CheckerPublic. permission = _handle_permission(_context, permission) # If class is not given we use the basic viewlet manager. if class_ is None: class_ = manager.ViewletManagerBase # Make sure that the template exists and that all low-level API methods # have the right permission. if template: template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) required['__getitem__'] = permission # Create a new class based on the template and class. new_class = manager.ViewletManager( name, provides, template=template, bases=(class_, )) else: # Create a new class based on the class. new_class = manager.ViewletManager(name, provides, bases=(class_, )) # Register some generic attributes with the security dictionary for attr_name in ('browserDefault', 'update', 'render', 'publishTraverse'): required[attr_name] = permission # Register the ``provides`` interface and register fields in the security # dictionary _handle_allowed_interface( _context, (provides,), permission, required) # Register the allowed interface and add the field's security entries _handle_allowed_interface( _context, allowed_interface, permission, required) # Register single allowed attributes in the security dictionary _handle_allowed_attributes( _context, allowed_attributes, permission, required) # Register interfaces _handle_for(_context, for_) zcml.interface(_context, view) # Create a checker for the viewlet manager checker.defineChecker(new_class, checker.Checker(required)) # register a viewlet manager _context.action( discriminator = ('viewletManager', for_, layer, view, name), callable = zcml.handler, args = ('registerAdapter', new_class, (for_, layer, view), provides, name, _context.info),) def viewletDirective( _context, name, permission, for_=Interface, layer=IDefaultBrowserLayer, view=IBrowserView, manager=interfaces.IViewletManager, class_=None, template=None, attribute='render', allowed_interface=None, allowed_attributes=None, **kwargs): # Security map dictionary required = {} # Get the permission; mainly to correctly handle CheckerPublic. permission = _handle_permission(_context, permission) # Either the class or template must be specified. if not (class_ or template): raise ConfigurationError("Must specify a class or template") # Make sure that all the non-default attribute specifications are correct. if attribute != 'render': if template: raise ConfigurationError( "Attribute and template cannot be used together.") # Note: The previous logic forbids this condition to evere occur. if not class_: raise ConfigurationError( "A class must be provided if attribute is used") # Make sure that the template exists and that all low-level API methods # have the right permission. if template: template = os.path.abspath(str(_context.path(template))) if not os.path.isfile(template): raise ConfigurationError("No such file", template) required['__getitem__'] = permission # Make sure the has the right form, if specified. if class_: if attribute != 'render': if not hasattr(class_, attribute): raise ConfigurationError( "The provided class doesn't have the specified attribute " ) if template: # Create a new class for the viewlet template and class. new_class = viewlet.SimpleViewletClass( template, bases=(class_, ), attributes=kwargs, name=name) else: if not hasattr(class_, 'browserDefault'): cdict = {'browserDefault': lambda self, request: (getattr(self, attribute), ())} else: cdict = {} cdict['__name__'] = name cdict['__page_attribute__'] = attribute cdict.update(kwargs) new_class = type(class_.__name__, (class_, viewlet.SimpleAttributeViewlet), cdict) if hasattr(class_, '__implements__'): classImplements(new_class, IBrowserPublisher) else: # Create a new class for the viewlet template alone. new_class = viewlet.SimpleViewletClass(template, name=name, attributes=kwargs) # Set up permission mapping for various accessible attributes _handle_allowed_interface( _context, allowed_interface, permission, required) _handle_allowed_attributes( _context, allowed_attributes, permission, required) _handle_allowed_attributes( _context, kwargs.keys(), permission, required) _handle_allowed_attributes( _context, (attribute, 'browserDefault', 'update', 'render', 'publishTraverse'), permission, required) # Register the interfaces. _handle_for(_context, for_) zcml.interface(_context, view) # Create the security checker for the new class checker.defineChecker(new_class, checker.Checker(required)) # register viewlet _context.action( discriminator = ('viewlet', for_, layer, view, manager, name), callable = zcml.handler, args = ('registerAdapter', new_class, (for_, layer, view, manager), interfaces.IViewlet, name, _context.info),) def _handle_permission(_context, permission): if permission == 'zope.Public': permission = checker.CheckerPublic return permission def _handle_allowed_interface(_context, allowed_interface, permission, required): # Allow access for all names defined by named interfaces if allowed_interface: for i in allowed_interface: _context.action( discriminator = None, callable = provideInterface, args = (None, i) ) for name in i: required[name] = permission def _handle_allowed_attributes(_context, allowed_attributes, permission, required): # Allow access for all named attributes if allowed_attributes: for name in allowed_attributes: required[name] = permission def _handle_for(_context, for_): if for_ is not None: _context.action( discriminator = None, callable = provideInterface, args = ('', for_) ) zope.viewlet-3.7.2/src/zope/viewlet/metadirectives.py0000644000175000017500000001421111376754171022702 0ustar tseavertseaver############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Viewlet metadirective $Id: metadirectives.py 112059 2010-05-05 19:40:35Z tseaver $ """ __docformat__ = 'restructuredtext' import zope.configuration.fields import zope.schema from zope.publisher.interfaces import browser from zope.security.zcml import Permission from zope.i18nmessageid import MessageFactory from zope.interface import Interface _ = MessageFactory('zope') from zope.viewlet import interfaces class IContentProvider(Interface): """A directive to register a simple content provider. Content providers are registered by their context (`for` attribute), the request (`layer` attribute) and the view (`view` attribute). They also must provide a name, so that they can be found using the TALES ``provider`` namespace. Other than that, content providers are just like any other views. """ view = zope.configuration.fields.GlobalObject( title=_("The view the content provider is registered for."), description=_("The view can either be an interface or a class. By " "default the provider is registered for all views, " "the most common case."), required=False, default=browser.IBrowserView) name = zope.schema.TextLine( title=_("The name of the content provider."), description=_("The name of the content provider is used in the TALES " "``provider`` namespace to look up the content " "provider."), required=True) for_ = zope.configuration.fields.GlobalObject( title=u"The interface or class this view is for.", required=False ) permission = Permission( title=u"Permission", description=u"The permission needed to use the view.", required=True ) class_ = zope.configuration.fields.GlobalObject( title=_("Class"), description=_("A class that provides attributes used by the view."), required=False, ) layer = zope.configuration.fields.GlobalInterface( title=_("The layer the view is in."), description=_(""" A skin is composed of layers. It is common to put skin specific views in a layer named after the skin. If the 'layer' attribute is not supplied, it defaults to 'default'."""), required=False, ) allowed_interface = zope.configuration.fields.Tokens( title=_("Interface that is also allowed if user has permission."), description=_(""" By default, 'permission' only applies to viewing the view and any possible sub views. By specifying this attribute, you can make the permission also apply to everything described in the supplied interface. Multiple interfaces can be provided, separated by whitespace."""), required=False, value_type=zope.configuration.fields.GlobalInterface(), ) allowed_attributes = zope.configuration.fields.Tokens( title=_("View attributes that are also allowed if the user" " has permission."), description=_(""" By default, 'permission' only applies to viewing the view and any possible sub views. By specifying 'allowed_attributes', you can make the permission also apply to the extra attributes on the view object."""), required=False, value_type=zope.configuration.fields.PythonIdentifier(), ) class ITemplatedContentProvider(IContentProvider): """A directive for registering a content provider that uses a page template to provide its content.""" template = zope.configuration.fields.Path( title=_("Content-generating template."), description=_("Refers to a file containing a page template (should " "end in extension ``.pt`` or ``.html``)."), required=False) class IViewletManagerDirective(ITemplatedContentProvider): """A directive to register a new viewlet manager. Viewlet manager registrations are very similar to content provider registrations, since they are just a simple extension of content providers. However, viewlet managers commonly have a specific provided interface, which is used to discriminate the viewlets they are providing. """ provides = zope.configuration.fields.GlobalInterface( title=_("The interface this viewlet manager provides."), description=_("A viewlet manager can provide an interface, which " "is used to lookup its contained viewlets."), required=False, default=interfaces.IViewletManager, ) class IViewletDirective(ITemplatedContentProvider): """A directive to register a new viewlet. Viewlets are content providers that can only be displayed inside a viewlet manager. Thus they are additionally discriminated by the manager. Viewlets can rely on the specified viewlet manager interface to provide their content. The viewlet directive also supports an undefined set of keyword arguments that are set as attributes on the viewlet after creation. Those attributes can then be used to implement sorting and filtering, for example. """ manager = zope.configuration.fields.GlobalObject( title=_("view"), description=u"The interface of the view this viewlet is for. " u"(default IBrowserView)", required=False, default=interfaces.IViewletManager) # Arbitrary keys and values are allowed to be passed to the viewlet. IViewletDirective.setTaggedValue('keyword_arguments', True) zope.viewlet-3.7.2/src/zope/viewlet/javascript_viewlet.pt0000644000175000017500000000015011376754171023567 0ustar tseavertseaver zope.viewlet-3.7.2/src/zope/viewlet/README.txt0000644000175000017500000010652411376754171021027 0ustar tseavertseaver============================= Viewlets and Viewlet Managers ============================= Let's start with some motivation. Using content providers allows us to insert one piece of HTML content. In most Web development, however, you are often interested in defining some sort of region and then allow developers to register content for those regions. >>> from zope.viewlet import interfaces Design Notes ------------ As mentioned above, besides inserting snippets of HTML at places, we more frequently want to define a region in our page and allow specialized content providers to be inserted based on configuration. Those specialized content providers are known as viewlets and are only available inside viewlet managers, which are just a more complex example of content providers. Unfortunately, the Java world does not implement this layer separately. The viewlet manager is most similar to a Java "channel", but we decided against using this name, since it is very generic and not very meaningful. The viewlet has no Java counterpart, since Java does not implement content providers using a component architecture and thus does not register content providers specifically for viewlet managers, which I believe makes the Java implementation less useful as a generic concept. In fact, the main design goal in the Java world is the implementation of reusable and sharable portlets. The scope for Zope 3 is larger, since we want to provide a generic framework for building pluggable user interfaces. The Viewlet Manager ------------------- In this implementation of viewlets, those regions are just content providers called viewlet managers that manage a special type of content providers known as viewlets. Every viewlet manager handles the viewlets registered for it: >>> class ILeftColumn(interfaces.IViewletManager): ... """Viewlet manager located in the left column.""" You can then create a viewlet manager using this interface now: >>> from zope.viewlet import manager >>> LeftColumn = manager.ViewletManager('left', ILeftColumn) Now we have to instantiate it: >>> import zope.interface >>> class Content(object): ... zope.interface.implements(zope.interface.Interface) >>> content = Content() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> from zope.publisher.interfaces.browser import IBrowserView >>> class View(object): ... zope.interface.implements(IBrowserView) ... def __init__(self, context, request): ... pass >>> view = View(content, request) >>> leftColumn = LeftColumn(content, request, view) So initially nothing gets rendered: >>> leftColumn.update() >>> leftColumn.render() u'' But now we register some viewlets for the manager >>> import zope.component >>> from zope.publisher.interfaces.browser import IDefaultBrowserLayer >>> class WeatherBox(object): ... zope.interface.implements(interfaces.IViewlet) ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... ... def update(self): ... pass ... ... def render(self): ... return u'
    It is sunny today!
    ' >>> # Create a security checker for viewlets. >>> from zope.security.checker import NamesChecker, defineChecker >>> viewletChecker = NamesChecker(('update', 'render')) >>> defineChecker(WeatherBox, viewletChecker) >>> zope.component.provideAdapter( ... WeatherBox, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, ILeftColumn), ... interfaces.IViewlet, name='weather') >>> from zope.location.interfaces import ILocation >>> class SportBox(object): ... zope.interface.implements(interfaces.IViewlet, ... ILocation) ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... ... def update(self): ... pass ... ... def render(self): ... return u'
    Patriots (23) : Steelers (7)
    ' >>> defineChecker(SportBox, viewletChecker) >>> zope.component.provideAdapter( ... SportBox, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, ILeftColumn), ... interfaces.IViewlet, name='sport') and thus the left column is filled. Note that also events get fired before viewlets are updated. We register a simple handler to demonstrate this behaviour. >>> from zope.contentprovider.interfaces import IBeforeUpdateEvent >>> events = [] >>> def handler(ev): ... events.append(ev) >>> zope.component.provideHandler(handler, (IBeforeUpdateEvent,)) >>> leftColumn.update() >>> [(ev, ev.object.__class__.__name__) for ev in events] [(, 'SportBox'), (, 'WeatherBox')] >>> print leftColumn.render()
    Patriots (23) : Steelers (7)
    It is sunny today!
    But this is of course pretty lame, since there is no way of specifying how the viewlets are put together. But we have a solution. The second argument of the ``ViewletManager()`` function is a template in which we can specify how the viewlets are put together: >>> import os, tempfile >>> temp_dir = tempfile.mkdtemp() >>> leftColTemplate = os.path.join(temp_dir, 'leftCol.pt') >>> open(leftColTemplate, 'w').write(''' ...
    ... ...
    ... ''') >>> LeftColumn = manager.ViewletManager('left', ILeftColumn, ... template=leftColTemplate) >>> leftColumn = LeftColumn(content, request, view) TODO: Fix this silly thing; viewlets should be directly available. As you can see, the viewlet manager provides a global ``options/viewlets`` variable that is an iterable of all the available viewlets in the correct order: >>> leftColumn.update() >>> print leftColumn.render().strip()
    Patriots (23) : Steelers (7)
    It is sunny today!
    If a viewlet provides ILocation the ``__name__`` attribute of the viewlet is set to the name under which the viewlet is registered. >>> [getattr(viewlet, '__name__', None) for viewlet in leftColumn.viewlets] [u'sport', None] You can also lookup the viewlets directly for management purposes: >>> leftColumn['weather'] >>> leftColumn.get('weather') The viewlet manager also provides the __contains__ method defined in IReadMapping: >>> 'weather' in leftColumn True >>> 'unknown' in leftColumn False If the viewlet is not found, then the expected behavior is provided: >>> leftColumn['stock'] Traceback (most recent call last): ... ComponentLookupError: No provider with name `stock` found. >>> leftColumn.get('stock') is None True Customizing the default Viewlet Manager --------------------------------------- One important feature of any viewlet manager is to be able to filter and sort the viewlets it is displaying. The default viewlet manager that we have been using in the tests above, supports filtering by access availability and sorting via the viewlet's ``__cmp__()`` method (default). You can easily override this default policy by providing a base viewlet manager class. In our case we will manage the viewlets using a global list: >>> shown = ['weather', 'sport'] The viewlet manager base class now uses this list: >>> class ListViewletManager(object): ... ... def filter(self, viewlets): ... viewlets = super(ListViewletManager, self).filter(viewlets) ... return [(name, viewlet) ... for name, viewlet in viewlets ... if name in shown] ... ... def sort(self, viewlets): ... viewlets = dict(viewlets) ... return [(name, viewlets[name]) for name in shown] Let's now create a new viewlet manager: >>> LeftColumn = manager.ViewletManager( ... 'left', ILeftColumn, bases=(ListViewletManager,), ... template=leftColTemplate) >>> leftColumn = LeftColumn(content, request, view) So we get the weather box first and the sport box second: >>> leftColumn.update() >>> print leftColumn.render().strip()
    It is sunny today!
    Patriots (23) : Steelers (7)
    Now let's change the order... >>> shown.reverse() and the order should switch as well: >>> leftColumn.update() >>> print leftColumn.render().strip()
    Patriots (23) : Steelers (7)
    It is sunny today!
    Of course, we also can remove a shown viewlet: >>> weather = shown.pop() >>> leftColumn.update() >>> print leftColumn.render().strip()
    Patriots (23) : Steelers (7)
    WeightOrderedViewletManager --------------------------- The weight ordered viewlet manager offers ordering viewlets by a additional weight argument. Viewlets which doesn't provide a weight attribute will get a weight of 0 (zero). Let's define a new column: >>> class IWeightedColumn(interfaces.IViewletManager): ... """Column with weighted viewlet manager.""" First register a template for the weight ordered viewlet manager: >>> weightedColTemplate = os.path.join(temp_dir, 'weightedColTemplate.pt') >>> open(weightedColTemplate, 'w').write(''' ...
    ... ...
    ... ''') And create a new weight ordered viewlet manager: >>> from zope.viewlet.manager import WeightOrderedViewletManager >>> WeightedColumn = manager.ViewletManager( ... 'left', IWeightedColumn, bases=(WeightOrderedViewletManager,), ... template=weightedColTemplate) >>> weightedColumn = WeightedColumn(content, request, view) Let's create some viewlets: >>> from zope.viewlet import viewlet >>> class FirstViewlet(viewlet.ViewletBase): ... ... weight = 1 ... ... def render(self): ... return u'
    first
    ' >>> class SecondViewlet(viewlet.ViewletBase): ... ... weight = 2 ... ... def render(self): ... return u'
    second
    ' >>> class ThirdViewlet(viewlet.ViewletBase): ... ... weight = 3 ... ... def render(self): ... return u'
    third
    ' >>> class UnWeightedViewlet(viewlet.ViewletBase): ... ... def render(self): ... return u'
    unweighted
    ' >>> defineChecker(FirstViewlet, viewletChecker) >>> defineChecker(SecondViewlet, viewletChecker) >>> defineChecker(ThirdViewlet, viewletChecker) >>> defineChecker(UnWeightedViewlet, viewletChecker) >>> zope.component.provideAdapter( ... ThirdViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='third') >>> zope.component.provideAdapter( ... FirstViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='first') >>> zope.component.provideAdapter( ... SecondViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='second') >>> zope.component.provideAdapter( ... UnWeightedViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IWeightedColumn), ... interfaces.IViewlet, name='unweighted') And check the order: >>> weightedColumn.update() >>> print weightedColumn.render().strip()
    unweighted
    first
    second
    third
    ConditionalViewletManager ------------------------- The conditional ordered viewlet manager offers ordering viewlets by a additional weight argument and filters by the available attribute if a supported by the viewlet. Viewlets which doesn't provide a available attribute will not get skipped. The default weight value for viewlets which doesn't provide a weight attribute is 0 (zero). Let's define a new column: >>> class IConditionalColumn(interfaces.IViewletManager): ... """Column with weighted viewlet manager.""" First register a template for the weight ordered viewlet manager: >>> conditionalColTemplate = os.path.join(temp_dir, ... 'conditionalColTemplate.pt') >>> open(conditionalColTemplate, 'w').write(''' ...
    ... ...
    ... ''') And create a new conditional viewlet manager: >>> from zope.viewlet.manager import ConditionalViewletManager >>> ConditionalColumn = manager.ViewletManager( ... 'left', IConditionalColumn, bases=(ConditionalViewletManager,), ... template=conditionalColTemplate) >>> conditionalColumn = ConditionalColumn(content, request, view) Let's create some viewlets. We also use the previous viewlets supporting no weight and or no available attribute: >>> from zope.viewlet import viewlet >>> class AvailableViewlet(viewlet.ViewletBase): ... ... weight = 4 ... ... available = True ... ... def render(self): ... return u'
    available
    ' >>> class UnAvailableViewlet(viewlet.ViewletBase): ... ... weight = 5 ... ... available = False ... ... def render(self): ... return u'
    not available
    ' >>> defineChecker(AvailableViewlet, viewletChecker) >>> defineChecker(UnAvailableViewlet, viewletChecker) >>> zope.component.provideAdapter( ... ThirdViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='third') >>> zope.component.provideAdapter( ... FirstViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='first') >>> zope.component.provideAdapter( ... SecondViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='second') >>> zope.component.provideAdapter( ... UnWeightedViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='unweighted') >>> zope.component.provideAdapter( ... AvailableViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='available') >>> zope.component.provideAdapter( ... UnAvailableViewlet, ... (zope.interface.Interface, IDefaultBrowserLayer, ... IBrowserView, IConditionalColumn), ... interfaces.IViewlet, name='unavailable') And check the order: >>> conditionalColumn.update() >>> print conditionalColumn.render().strip()
    unweighted
    first
    second
    third
    available
    Viewlet Base Classes -------------------- To make the creation of viewlets simpler, a set of useful base classes and helper functions are provided. The first class is a base class that simply defines the constructor: >>> base = viewlet.ViewletBase('context', 'request', 'view', 'manager') >>> base.context 'context' >>> base.request 'request' >>> base.__parent__ 'view' >>> base.manager 'manager' But a default ``render()`` method implementation is not provided: >>> base.render() Traceback (most recent call last): ... NotImplementedError: `render` method must be implemented by subclass. If you have already an existing class that produces the HTML content in some method, then the ``SimpleAttributeViewlet`` might be for you, since it can be used to convert any class quickly into a viewlet: >>> class FooViewlet(viewlet.SimpleAttributeViewlet): ... __page_attribute__ = 'foo' ... ... def foo(self): ... return 'output' The `__page_attribute__` attribute provides the name of the function to call for rendering. >>> foo = FooViewlet('context', 'request', 'view', 'manager') >>> foo.foo() 'output' >>> foo.render() 'output' If you specify `render` as the attribute an error is raised to prevent infinite recursion: >>> foo.__page_attribute__ = 'render' >>> foo.render() Traceback (most recent call last): ... AttributeError: render The same is true if the specified attribute does not exist: >>> foo.__page_attribute__ = 'bar' >>> foo.render() Traceback (most recent call last): ... AttributeError: 'FooViewlet' object has no attribute 'bar' To create simple template-based viewlets you can use the ``SimpleViewletClass()`` function. This function is very similar to its view equivalent and is used by the ZCML directives to create viewlets. The result of this function call will be a fully functional viewlet class. Let's start by simply specifying a template only: >>> template = os.path.join(temp_dir, 'demoTemplate.pt') >>> open(template, 'w').write('''
    contents
    ''') >>> Demo = viewlet.SimpleViewletClass(template) >>> print Demo(content, request, view, manager).render()
    contents
    Now let's additionally specify a class that can provide additional features: >>> class MyViewlet(object): ... myAttribute = 8 >>> Demo = viewlet.SimpleViewletClass(template, bases=(MyViewlet,)) >>> MyViewlet in Demo.__bases__ True >>> Demo(content, request, view, manager).myAttribute 8 The final important feature is the ability to pass in further attributes to the class: >>> Demo = viewlet.SimpleViewletClass( ... template, attributes={'here': 'now', 'lucky': 3}) >>> demo = Demo(content, request, view, manager) >>> demo.here 'now' >>> demo.lucky 3 As for all views, they must provide a name that can also be passed to the function: >>> Demo = viewlet.SimpleViewletClass(template, name='demoViewlet') >>> demo = Demo(content, request, view, manager) >>> demo.__name__ 'demoViewlet' In addition to the the generic viewlet code above, the package comes with two viewlet base classes and helper functions for inserting CSS and Javascript links into HTML headers, since those two are so very common. I am only going to demonstrate the helper functions here, since those demonstrations will fully demonstrate the functionality of the base classes as well. The viewlet will look up the resource it was given and tries to produce the absolute URL for it: >>> class JSResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/resource.js' >>> zope.component.provideAdapter( ... JSResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='resource.js') >>> JSViewlet = viewlet.JavaScriptViewlet('resource.js') >>> print JSViewlet(content, request, view, manager).render().strip() There is also a javascript viewlet base class which knows how to render more then one javascript resource file: >>> class JSSecondResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/second-resource.js' >>> zope.component.provideAdapter( ... JSSecondResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='second-resource.js') >>> JSBundleViewlet = viewlet.JavaScriptBundleViewlet(('resource.js', ... 'second-resource.js')) >>> print JSBundleViewlet(content, request, view, manager).render().strip() The same works for the CSS resource viewlet: >>> class CSSResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/resource.css' >>> zope.component.provideAdapter( ... CSSResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='resource.css') >>> CSSViewlet = viewlet.CSSViewlet('resource.css') >>> print CSSViewlet(content, request, view, manager).render().strip() You can also change the media type and the rel attribute: >>> CSSViewlet = viewlet.CSSViewlet('resource.css', media='print', rel='css') >>> print CSSViewlet(content, request, view, manager).render().strip() There is also a bundle viewlet for CSS links: >>> class CSSPrintResource(object): ... def __init__(self, request): ... self.request = request ... ... def __call__(self): ... return '/@@/print-resource.css' >>> zope.component.provideAdapter( ... CSSPrintResource, ... (IDefaultBrowserLayer,), ... zope.interface.Interface, name='print-resource.css') >>> items = [] >>> items.append({'path':'resource.css', 'rel':'stylesheet', 'media':'all'}) >>> items.append({'path':'print-resource.css', 'media':'print'}) >>> CSSBundleViewlet = viewlet.CSSBundleViewlet(items) >>> print CSSBundleViewlet(content, request, view, manager).render().strip() A Complex Example ----------------- The Data ~~~~~~~~ So far we have only demonstrated simple (maybe overly trivial) use cases of the viewlet system. In the following example, we are going to develop a generic contents view for files. The step is to create a file component: >>> class IFile(zope.interface.Interface): ... data = zope.interface.Attribute('Data of file.') >>> class File(object): ... zope.interface.implements(IFile) ... def __init__(self, data=''): ... self.__name__ = '' ... self.data = data Since we want to also provide the size of a file, here a simple implementation of the ``ISized`` interface: >>> from zope import size >>> class FileSized(object): ... zope.interface.implements(size.interfaces.ISized) ... zope.component.adapts(IFile) ... ... def __init__(self, file): ... self.file = file ... ... def sizeForSorting(self): ... return 'byte', len(self.file.data) ... ... def sizeForDisplay(self): ... return '%i bytes' %len(self.file.data) >>> zope.component.provideAdapter(FileSized) We also need a container to which we can add files: >>> class Container(dict): ... def __setitem__(self, name, value): ... value.__name__ = name ... super(Container, self).__setitem__(name, value) Here is some sample data: >>> container = Container() >>> container['test.txt'] = File('Hello World!') >>> container['mypage.html'] = File('Hello World!') >>> container['data.xml'] = File('Hello World!') The View ~~~~~~~~ The contents view of the container should iterate through the container and represent the files in a table: >>> contentsTemplate = os.path.join(temp_dir, 'contents.pt') >>> open(contentsTemplate, 'w').write(''' ... ... ...

    Contents

    ...
    ... ... ... ''') >>> from zope.browserpage.simpleviewclass import SimpleViewClass >>> Contents = SimpleViewClass(contentsTemplate, name='contents.html') The Viewlet Manager ~~~~~~~~~~~~~~~~~~~ Now we have to write our own viewlet manager. In this case we cannot use the default implementation, since the viewlets will be looked up for each different item: >>> shownColumns = [] >>> class ContentsViewletManager(object): ... zope.interface.implements(interfaces.IViewletManager) ... index = None ... ... def __init__(self, context, request, view): ... self.context = context ... self.request = request ... self.__parent__ = view ... ... def update(self): ... rows = [] ... for name, value in self.context.items(): ... rows.append( ... [zope.component.getMultiAdapter( ... (value, self.request, self.__parent__, self), ... interfaces.IViewlet, name=colname) ... for colname in shownColumns]) ... [entry.update() for entry in rows[-1]] ... self.rows = rows ... ... def render(self, *args, **kw): ... return self.index(*args, **kw) Now we need a template to produce the contents table: >>> tableTemplate = os.path.join(temp_dir, 'table.pt') >>> open(tableTemplate, 'w').write(''' ... ... ... ... ...
    ... ...
    ... ''') From the two pieces above, we can generate the final viewlet manager class and register it (it's a bit tedious, I know): >>> from zope.browserpage import ViewPageTemplateFile >>> ContentsViewletManager = type( ... 'ContentsViewletManager', (ContentsViewletManager,), ... {'index': ViewPageTemplateFile(tableTemplate)}) >>> zope.component.provideAdapter( ... ContentsViewletManager, ... (Container, IDefaultBrowserLayer, zope.interface.Interface), ... interfaces.IViewletManager, name='contents') Since we have not defined any viewlets yet, the table is totally empty: >>> contents = Contents(container, request) >>> print contents().strip()

    Contents

    The Viewlets and the Final Result ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Now let's create a first viewlet for the manager... >>> class NameViewlet(object): ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... self.context = context ... ... def update(self): ... pass ... ... def render(self): ... return self.context.__name__ and register it: >>> zope.component.provideAdapter( ... NameViewlet, ... (IFile, IDefaultBrowserLayer, ... zope.interface.Interface, interfaces.IViewletManager), ... interfaces.IViewlet, name='name') Note how you register the viewlet on ``IFile`` and not on the container. Now we should be able to see the name for each file in the container: >>> print contents().strip()

    Contents

    Waaa, nothing there! What happened? Well, we have to tell our user preferences that we want to see the name as a column in the table: >>> shownColumns = ['name'] >>> print contents().strip()

    Contents

    mypage.html
    data.xml
    test.txt
    Let's now write a second viewlet that will display the size of the object for us: >>> class SizeViewlet(object): ... ... def __init__(self, context, request, view, manager): ... self.__parent__ = view ... self.context = context ... ... def update(self): ... pass ... ... def render(self): ... return size.interfaces.ISized(self.context).sizeForDisplay() >>> zope.component.provideAdapter( ... SizeViewlet, ... (IFile, IDefaultBrowserLayer, ... zope.interface.Interface, interfaces.IViewletManager), ... interfaces.IViewlet, name='size') After we added it to the list of shown columns, >>> shownColumns = ['name', 'size'] we can see an entry for it: >>> print contents().strip()

    Contents

    mypage.html 38 bytes
    data.xml 31 bytes
    test.txt 12 bytes
    If we switch the two columns around, >>> shownColumns = ['size', 'name'] the result will be >>> print contents().strip()

    Contents

    38 bytes mypage.html
    31 bytes data.xml
    12 bytes test.txt
    Supporting Sorting ~~~~~~~~~~~~~~~~~~ Oftentimes you also want to batch and sort the entries in a table. Since those two features are not part of the view logic, they should be treated with independent components. In this example, we are going to only implement sorting using a simple utility: >>> class ISorter(zope.interface.Interface): ... ... def sort(values): ... """Sort the values.""" >>> class SortByName(object): ... zope.interface.implements(ISorter) ... ... def sort(self, values): ... return sorted(values, lambda x, y: cmp(x.__name__, y.__name__)) >>> zope.component.provideUtility(SortByName(), name='name') >>> class SortBySize(object): ... zope.interface.implements(ISorter) ... ... def sort(self, values): ... return sorted( ... values, ... lambda x, y: cmp(size.interfaces.ISized(x).sizeForSorting(), ... size.interfaces.ISized(y).sizeForSorting())) >>> zope.component.provideUtility(SortBySize(), name='size') Note that we decided to give the sorter utilities the same name as the corresponding viewlet. This convention will make our implementation of the viewlet manager much simpler: >>> sortByColumn = '' >>> class SortedContentsViewletManager(object): ... zope.interface.implements(interfaces.IViewletManager) ... index = None ... ... def __init__(self, context, request, view): ... self.context = context ... self.request = request ... self.__parent__ = view ... ... def update(self): ... values = self.context.values() ... ... if sortByColumn: ... sorter = zope.component.queryUtility(ISorter, sortByColumn) ... if sorter: ... values = sorter.sort(values) ... ... rows = [] ... for value in values: ... rows.append( ... [zope.component.getMultiAdapter( ... (value, self.request, self.__parent__, self), ... interfaces.IViewlet, name=colname) ... for colname in shownColumns]) ... [entry.update() for entry in rows[-1]] ... self.rows = rows ... ... def render(self, *args, **kw): ... return self.index(*args, **kw) As you can see, the concern of sorting is cleanly separated from generating the view code. In MVC terms that means that the controller (sort) is logically separated from the view (viewlets). Let's now do the registration dance for the new viewlet manager. We simply override the existing registration: >>> SortedContentsViewletManager = type( ... 'SortedContentsViewletManager', (SortedContentsViewletManager,), ... {'index': ViewPageTemplateFile(tableTemplate)}) >>> zope.component.provideAdapter( ... SortedContentsViewletManager, ... (Container, IDefaultBrowserLayer, zope.interface.Interface), ... interfaces.IViewletManager, name='contents') Finally we sort the contents by name: >>> shownColumns = ['name', 'size'] >>> sortByColumn = 'name' >>> print contents().strip()

    Contents

    data.xml 31 bytes
    mypage.html 38 bytes
    test.txt 12 bytes
    Now let's sort by size: >>> sortByColumn = 'size' >>> print contents().strip()

    Contents

    test.txt 12 bytes
    data.xml 31 bytes
    mypage.html 38 bytes
    That's it! As you can see, in a few steps we have built a pretty flexible contents view with selectable columns and sorting. However, there is a lot of room for extending this example: - Table Header: The table header cell for each column should be a different type of viewlet, but registered under the same name. The column header viewlet also adapts the container not the item. The header column should also be able to control the sorting. - Batching: A simple implementation of batching should work very similar to the sorting feature. Of course, efficient implementations should somehow combine batching and sorting more effectively. - Sorting in ascending and descending order: Currently, you can only sort from the smallest to the highest value; however, this limitation is almost superficial and can easily be removed by making the sorters a bit more flexible. - Further Columns: For a real application, you would want to implement other columns, of course. You would also probably want some sort of fallback for the case that a viewlet is not found for a particular container item and column. Cleanup ------- >>> import shutil >>> shutil.rmtree(temp_dir) zope.viewlet-3.7.2/src/zope/viewlet/javascript_bundle_viewlet.pt0000644000175000017500000000024311376754171025123 0ustar tseavertseaver zope.viewlet-3.7.2/src/zope/viewlet/configure.zcml0000644000175000017500000000076311376754171022177 0ustar tseavertseaver zope.viewlet-3.7.2/src/zope/viewlet/css_viewlet.pt0000644000175000017500000000030511376754171022213 0ustar tseavertseaver zope.viewlet-3.7.2/src/zope/viewlet/directives.txt0000644000175000017500000003065411376754171022233 0ustar tseavertseaver================================ The ``viewletManager`` Directive ================================ The ``viewletManager`` directive allows you to quickly register a new viewlet manager without worrying about the details of the ``adapter`` directive. Before we can use the directives, we have to register their handlers by executing the package's meta configuration: >>> from zope.configuration import xmlconfig >>> context = xmlconfig.string(''' ... ... ... ... ''') Now we can register a viewlet manager: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Let's make sure the directive has really issued a sensible adapter registration; to do that, we create some dummy content, request and view objects: >>> import zope.interface >>> class Content(object): ... zope.interface.implements(zope.interface.Interface) >>> content = Content() >>> from zope.publisher.browser import TestRequest >>> request = TestRequest() >>> from zope.publisher.browser import BrowserView >>> view = BrowserView(content, request) Now let's lookup the manager. This particular registration is pretty boring: >>> import zope.component >>> from zope.viewlet import interfaces >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ... interfaces.IViewletManager, name='defaultmanager') >>> manager object ...> >>> interfaces.IViewletManager.providedBy(manager) True >>> manager.template is None True >>> manager.update() >>> manager.render() u'' However, this registration is not very useful, since we did specify a specific viewlet manager interface, a specific content interface, specific view or specific layer. This means that all viewlets registered will be found. The first step to effectively using the viewlet manager directive is to define a special viewlet manager interface: >>> class ILeftColumn(interfaces.IViewletManager): ... """Left column of my page.""" Now we can register register a manager providing this interface: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager object ...> >>> ILeftColumn.providedBy(manager) True >>> manager.template is None True >>> manager.update() >>> manager.render() u'' Next let's see what happens, if we specify a template for the viewlet manager: >>> import os, tempfile >>> temp_dir = tempfile.mkdtemp() >>> leftColumnTemplate = os.path.join(temp_dir, 'leftcolumn.pt') >>> open(leftColumnTemplate, 'w').write(''' ...
    ...
    ...
    ... ''') >>> context = xmlconfig.string(''' ... ... ... ... ''' %leftColumnTemplate, context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager object ...> >>> ILeftColumn.providedBy(manager) True >>> manager.template ...>> >>> manager.update() >>> print manager.render().strip()
    Additionally you can specify a class that will serve as a base to the default viewlet manager or be a viewlet manager in its own right. In our case we will provide a custom implementation of the ``sort()`` method, which will sort by a weight attribute in the viewlet: >>> class WeightBasedSorting(object): ... def sort(self, viewlets): ... return sorted(viewlets, ... lambda x, y: cmp(x[1].weight, y[1].weight)) >>> context = xmlconfig.string(''' ... ... ... ... ''' %leftColumnTemplate, context=context) >>> manager = zope.component.getMultiAdapter( ... (content, request, view), ILeftColumn, name='leftcolumn') >>> manager object ...> >>> manager.__class__.__bases__ (, ) >>> ILeftColumn.providedBy(manager) True >>> manager.template ...>> >>> manager.update() >>> print manager.render().strip()
    Finally, if a non-existent template is specified, an error is raised: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-7.8 ConfigurationError: ('No such file', '...foo.pt') ========================= The ``viewlet`` Directive ========================= Now that we have a viewlet manager, we have to register some viewlets for it. The ``viewlet`` directive is similar to the ``viewletManager`` directive, except that the viewlet is also registered for a particular manager interface, as seen below: >>> weatherTemplate = os.path.join(temp_dir, 'weather.pt') >>> open(weatherTemplate, 'w').write(''' ...
    sunny
    ... ''') >>> context = xmlconfig.string(''' ... ... ... ... ''' % weatherTemplate, context=context) If we look into the adapter registry, we will find the viewlet: >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='weather') >>> viewlet.render().strip() u'
    sunny
    ' >>> viewlet.extra_string_attributes u'can be specified' The manager now also gives us the output of the one and only viewlet: >>> manager.update() >>> print manager.render().strip()
    sunny
    Let's now ensure that we can also specify a viewlet class: >>> class Weather(object): ... weight = 0 >>> context = xmlconfig.string(''' ... ... ... ... ''' % weatherTemplate, context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='weather2') >>> viewlet().strip() u'
    sunny
    ' Okay, so the template-driven cases work. But just specifying a class should also work: >>> class Sport(object): ... weight = 0 ... def __call__(self): ... return u'Red Sox vs. White Sox' >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, name='sport') >>> viewlet() u'Red Sox vs. White Sox' It should also be possible to specify an alternative attribute of the class to be rendered upon calling the viewlet: >>> class Stock(object): ... weight = 0 ... def getStockTicker(self): ... return u'SRC $5.19' >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='stock') >>> viewlet.render() u'SRC $5.19' A final feature the ``viewlet`` directive is that it supports the specification of any number of keyword arguments: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) >>> viewlet = zope.component.getMultiAdapter( ... (content, request, view, manager), interfaces.IViewlet, ... name='stock2') >>> viewlet.weight u'8' Error Scenarios --------------- Neither the class or template have been specified: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-7.8 ConfigurationError: Must specify a class or template The specified attribute is not ``__call__``, but also a template has been specified: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-9.8 ConfigurationError: Attribute and template cannot be used together. Now, we are not specifying a template, but a class that does not have the specified attribute: >>> context = xmlconfig.string(''' ... ... ... ... ''', context=context) Traceback (most recent call last): ... ZopeXMLConfigurationError: File "", line 3.2-9.8 ConfigurationError: The provided class doesn't have the specified attribute Cleanup ------- >>> import shutil >>> shutil.rmtree(temp_dir) zope.viewlet-3.7.2/src/zope/viewlet/viewlet.py0000644000175000017500000001513611376754171021360 0ustar tseavertseaver############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Viewlet implementation $Id: viewlet.py 112059 2010-05-05 19:40:35Z tseaver $ """ __docformat__ = 'restructuredtext' import os import sys import zope.interface from zope.traversing import api from zope.publisher.browser import BrowserView from zope.viewlet import interfaces from zope.browserpage import simpleviewclass from zope.browserpage import ViewPageTemplateFile class ViewletBase(BrowserView): """Viewlet adapter class used in meta directive as a mixin class.""" zope.interface.implements(interfaces.IViewlet) def __init__(self, context, request, view, manager): super(ViewletBase, self).__init__(context, request) self.__parent__ = view self.context = context self.request = request self.manager = manager def update(self): pass def render(self): raise NotImplementedError( '`render` method must be implemented by subclass.') class SimpleAttributeViewlet(ViewletBase): """A viewlet that uses a specified method to produce its content.""" def render(self, *args, **kw): # If a class doesn't provide it's own call, then get the attribute # given by the browser default. attr = self.__page_attribute__ if attr == 'render': raise AttributeError("render") meth = getattr(self, attr) return meth(*args, **kw) class simple(simpleviewclass.simple): """Simple viewlet class supporting the ``render()`` method.""" render = simpleviewclass.simple.__call__ def SimpleViewletClass(template, offering=None, bases=(), attributes=None, name=u''): """A function that can be used to generate a viewlet from a set of information. """ # Get the current frame if offering is None: offering = sys._getframe(1).f_globals # Create the base class hierarchy bases += (simple, ViewletBase) attrs = {'index' : ViewPageTemplateFile(template, offering), '__name__' : name} if attributes: attrs.update(attributes) # Generate a derived view class. class_ = type("SimpleViewletClass from %s" % template, bases, attrs) return class_ class ResourceViewletBase(object): """A simple viewlet for inserting references to resources. This is an abstract class that is expected to be used as a base only. """ _path = None def getURL(self): resource = api.traverse(self.context, '++resource++' + self._path, request=self.request) return resource() def render(self, *args, **kw): return self.index(*args, **kw) def JavaScriptViewlet(path): """Create a viewlet that can simply insert a javascript link.""" src = os.path.join(os.path.dirname(__file__), 'javascript_viewlet.pt') klass = type('JavaScriptViewlet', (ResourceViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_path': path}) return klass class CSSResourceViewletBase(ResourceViewletBase): _media = 'all' _rel = 'stylesheet' def getMedia(self): return self._media def getRel(self): return self._rel def CSSViewlet(path, media="all", rel="stylesheet"): """Create a viewlet that can simply insert a CSS link.""" src = os.path.join(os.path.dirname(__file__), 'css_viewlet.pt') klass = type('CSSViewlet', (CSSResourceViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_path': path, '_media':media, '_rel':rel}) return klass class ResourceBundleViewletBase(object): """A simple viewlet for inserting references to different resources. This is an abstract class that is expected to be used as a base only. """ _paths = None def getResources(self): resources = [] append = resources.append for path in self._paths: append(api.traverse(self.context, '++resource++' + path, request=self.request)) return resources def render(self, *args, **kw): return self.index(*args, **kw) def JavaScriptBundleViewlet(paths): """Create a viewlet that can simply insert javascript links.""" src = os.path.join(os.path.dirname(__file__), 'javascript_bundle_viewlet.pt') klass = type('JavaScriptBundleViewlet', (ResourceBundleViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_paths': paths}) return klass class CSSResourceBundleViewletBase(object): """A simple viewlet for inserting css references to different resources. There is a tuple or list of dict used for the different resource descriptions. The list of dict uses the following format: ({path:'the path', media:'all', rel:'stylesheet'},...) The default values for media is ``all`` and the default value for rel is ``stylesheet``. The path must be set there is no default value for the path attribute. This is an abstract class that is expected to be used as a base only. """ _items = None def getResources(self): resources = [] append = resources.append for item in self._items: info = {} info['url'] = api.traverse(self.context, '++resource++' + item.get('path'), request=self.request) info['media'] = item.get('media', 'all') info['rel'] = item.get('rel', 'stylesheet') append(info) return resources def render(self, *args, **kw): return self.index(*args, **kw) def CSSBundleViewlet(items): """Create a viewlet that can simply insert css links.""" src = os.path.join(os.path.dirname(__file__), 'css_bundle_viewlet.pt') klass = type('CSSBundleViewlet', (CSSResourceBundleViewletBase, ViewletBase), {'index': ViewPageTemplateFile(src), '_items': items}) return klass zope.viewlet-3.7.2/src/zope/viewlet/tests.py0000644000175000017500000000557111376754171021045 0ustar tseavertseaver############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Viewlet tests $Id: tests.py 112059 2010-05-05 19:40:35Z tseaver $ """ __docformat__ = 'restructuredtext' import os import doctest import sys import unittest import zope.component from zope.testing import cleanup from zope.traversing.testing import setUp as traversingSetUp from zope.component import eventtesting def setUp(test): cleanup.setUp() eventtesting.setUp() traversingSetUp() # resource namespace setup from zope.traversing.interfaces import ITraversable from zope.traversing.namespace import resource zope.component.provideAdapter( resource, (None,), ITraversable, name = "resource") zope.component.provideAdapter( resource, (None, None), ITraversable, name = "resource") from zope.browserpage import metaconfigure from zope.contentprovider import tales metaconfigure.registerType('provider', tales.TALESProviderExpression) def tearDown(test): cleanup.tearDown() class FakeModule(object): """A fake module.""" def __init__(self, dict): self.__dict = dict def __getattr__(self, name): try: return self.__dict[name] except KeyError: raise AttributeError(name) def directivesSetUp(test): setUp(test) test.globs['__name__'] = 'zope.viewlet.directives' sys.modules['zope.viewlet.directives'] = FakeModule(test.globs) def directivesTearDown(test): tearDown(test) del sys.modules[test.globs['__name__']] test.globs.clear() def test_suite(): return unittest.TestSuite(( doctest.DocFileSuite('README.txt', setUp=setUp, tearDown=tearDown, optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS, globs = {'__file__': os.path.join( os.path.dirname(__file__), 'README.txt')} ), doctest.DocFileSuite('directives.txt', setUp=directivesSetUp, tearDown=directivesTearDown, optionflags=doctest.NORMALIZE_WHITESPACE|doctest.ELLIPSIS, globs = {'__file__': os.path.join( os.path.dirname(__file__), 'directives.txt')} ), )) if __name__ == '__main__': unittest.main(defaultTest='test_suite') zope.viewlet-3.7.2/src/zope/viewlet/__init__.py0000644000175000017500000000127311376754171021435 0ustar tseavertseaver############################################################################## # # Copyright (c) 2004 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """ $Id: __init__.py 112059 2010-05-05 19:40:35Z tseaver $ """ zope.viewlet-3.7.2/src/zope/__init__.py0000644000175000017500000000007011376754171017750 0ustar tseavertseaver__import__('pkg_resources').declare_namespace(__name__) zope.viewlet-3.7.2/LICENSE.txt0000644000175000017500000000402611376754171015723 0ustar tseavertseaverZope Public License (ZPL) Version 2.1 A copyright notice accompanies this license document that identifies the copyright holders. This license has been certified as open source. It has also been designated as GPL compatible by the Free Software Foundation (FSF). Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions in source code must retain the accompanying copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the accompanying copyright notice, this list of conditions, and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Names of the copyright holders must not be used to endorse or promote products derived from this software without prior written permission from the copyright holders. 4. The right to distribute this software or to use it for any purpose does not give you the right to use Servicemarks (sm) or Trademarks (tm) of the copyright holders. Use of them is covered by separate agreement with the copyright holders. 5. If any files are modified, you must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.