ZPT Basics (part 2) - Submitting To The King (
Page 8 of 9 )
You may remember, from the first part of this series, an example
involving a form and a form processor. In that example, I used two Zope
objects - a single DTML Document to display the form, and a separate
page template to process the form input and generate appropriate output.
However, ZPT provides an elegant method to combine those two pages into
one via the "submit" variable.
In order to better understand this, create a Page Template named
"DualPurposeForm" and add the following code to it:
<div tal:define="global submit request/form/submit | nothing"
tal:condition="not:submit">
<form action="DualPurposeForm" method="POST">
Species:
<br>
<input name="species">
<p>
Home planet:
<br>
<input name="planet"></p>
<p>
Distance (light years) from Earth:
<br>
<input name="distance"></p>
<p>
<input type="Submit" name="submit" value="Beam Me Up, Scotty"></p>
</form> </div>
<div tal:condition="submit">
<p>Welcome to Earth, <b tal:content="request/form/species">alien species
name</b> from the planet <b tal:content="request/form/planet">planet
name</b>. </p>
<p>How was your journey?
Travelling <b tal:content="request/form/distance">distance</b> light
years must be quite a shock
to the system. Why don't you relax and have a drink?</p>
</div>
There are two conditional tests in the template above, both keyed on the
presence or absence of the "submit" variable. The first time the
template is accessed, the "submit" variable will not exist, and
therefore the first conditional test will evaluate to true and the form
will be displayed. Once the form has been submitted, the same template
will be called again. However, this time around, the "submit" variable
will exist in the request context, and so the second part of the
template will be displayed.
There are a couple of things to note in the example above. First, the
template variable "submit", which is set depending on the presence of a
form "submit" variable in the request object. In case this variable does
not exist, the template variable "submit" is set to the special value
"nothing". You may remember, again from the first part of this series,
that "nothing" is a special TAL variable used to represent a null value.
Second, the usage of the "not" keyword in the first conditional test.
This keyword evaluates the TALES expression that follows, and returns
the Boolean reverse of the result. Thus, the first time the template is
accessed, the value of the "submit" variable will be set to null, the
TALES expression will evaluate to Boolean false and the "not" negation
will convert it to Boolean true...which serves as a flag to display the
empty form.
This technique makes it possible to reduce the number of objects used,
and perhaps make your Zope object collection easier to handle.