A dynamic hello world

You should first install a sandbox as explained in the Writing your first Zope 3 Application page.

Python class

In the src/helloworld directory, create a hello.py with a few lines of Python code:

class Hello(object):
    def getText(self):
      name = self.request.get('name')
      if name:
        return "Hello %s !" % name
      else:
        return "Hello ! What's your name ?"

This class defines a browser view in charge of displaying some content.

HTML template

We now need a page template to render the page content in html. So let's add a hello.pt in the src/helloworld directory:

<html>
  <head>
    <title>hello world page</title>
  </head>
  <body>
    <div tal:content="view/getText">
      fake content
    </div>
  </body>
</html>

The tal:content directive tells zope to replace the fake content of the tag with the output of the getText method of the view class. ZCML registration

The next step is to associate the view class, the template and the page name. This is done with a simple XML configuration language (ZCML). Edit the existing file called configure.zcml and add the following content before the final </configure>:

<browser:page name="hello.html"
              for="*"
              class=".hello.Hello"
              template="hello.pt"
              permission="zope.Public" />

This declaration means: "there is a web page called hello.html, available for any content, managed by the view class Hello, rendered by the template hello.pt, and this page is public.

Since we are using the browser XML namespace, we need to declare it in the configure directive. Modify the first lines of the configure.zcml file so it looks like this (You can skip this step if the browser namespace is already there from the static hello world view):

<configure xmlns="http://namespaces.zope.org/zope"
           xmlns:browser="http://namespaces.zope.org/browser">

Restart your application, then visit the following URL:

http://127.0.0.1:8080/hello.html

You should then see the following text in your browser:

Hello ! What's your name ?

You can pass a parameter to the Hello view class, by visiting the following URL:

http://127.0.0.1:8080/hello.html?name=World

You should then see the following text:

Hello World !


( 102 subscribers )