Basic recipe for a Five view

This recipe is addressed more to the zope2/plone developer with a bit of knowledge of the zope3 universe, but not much experience in implementing the new practices.

Simply put, Five views are just like TTW python scripts, except without the limited forced security, and with the possibility to integrate them in unit testing and adapt them to other protocols then just http.

First, things should be done the newly recommended "Zope3 ways". That means creating a new package under the Products folder, or, if pythonproducts is used, anywhere in the python packages path.

Let's name this package "views_test". Make it a python package by placing an empty __init__.py file inside. We'll place the views under a 'browser' package, so we need to create a new folder called 'browser' with an empty __init__.py file as well.

Inside the browser package, we'll create a 'testing' module, with the following content:

from zope.interface import Interface, implements
from Products.CMFPlone import utils

class ITesting(Interface):
    def drink():
        """Drinks the cool aid"""

class Testing(utils.BrowserView):
    implements(ITesting)

    def drink(self):
        context=utils.context(self)
portal_url = context.portal_url()
        return "We drank the cool aid at %s" % portal_url

The interface declaration is not needed, and it's not necesary for the view to implement a certain interface, but it makes documenting, configuring and possibly future extending the software easier.

Configuring zope to load the view

Best practices is to place configuration files (configure.zcml) in the closest package to which they belong, so we'll have to configure zope to look in the 'browser' package for zcmls as well. To do this, edit the views_test/configure.zcml file and place a simple directive to load the browser package.

<include package=".browser" />
The configure.zcml file for the browser package will contain
<configure xmlns="http://namespaces.zope.org/zope"
           xmlns:browser="http://namespaces.zope.org/browser"
          xmlns:five="http://namespaces.zope.org/five">

<browser:page
    for="*"
    name="testing_view"
    class=".testing.Testing"
    permission="zope.Public"
template="testview"
    allowed_interface=".testing.ITesting"
allowed_attributes="drink"
    />

</configure>

The TAL template, testview.pt is like this:

<html>
  <head>
    <title tal:content="template/title">The title</title>
  </head>
  <body tal:define="view context/@@testing_view">
<span tal:content="view/drink" />
  </body>
</html>

It doesn't use the standard main_template macros, but this can be easily integrated.

Comments