quick search:
 

Using non-declared variables on DTML

Submitted by: Wolfox
Last Edited: 2001-08-09

Category: Python(Script)

Average rating is: 2.0 out of 5 (1 ratings)

Description:
PHP programmers are used to use 'if' constructs to test non-defined variables. The same throws an exception on Zope that may be hard to deal with. This little script can be called from a DTML method or document to safeguard the needed variables. It takes a list (vars) containing the names of the vars to be checked.

Source (Text):
import string

for var in vars:
  if context.REQUEST.has_key(var):
    t = context.REQUEST[var]
    if same_type(t, ""):  # if it's a string, strip whitespace from it
      t = string.strip(t)
      context.REQUEST.set(var, t)
  else:
    context.REQUEST.set(var, None)

Explanation:
The for loop iterates over the list, taking each variable name and checking
if it's defined on REQUEST. If not defined, define it with None. If defined,
it checks if it's a string; if so, it strips it (always recommended with
web apps).

That way you can test for a not-always defined variable on your DTML method
with dtml-if, instead of complicated dtml-try/except combinations with
dtml-if.


Comments:

Don't need to predeclare to use in dtml-if by pup - 2001-08-14
In DTML, the statement

  <dtml-if "varname == 'hello'">

will raise an exception if varname isn't defined, but

  <dtml-if varname>

works fine; true if defined & true, false if not defined
or not true.

So, there's no need to "predeclare" variables just to use
them in dtml-if testing.

If you need to check something about a variable, and can't
be sure if its declared or not, you can use this:

  <dtml-if "varname and varname == 'Hello'">

which will not raise an exception if varname is not declared.


BTW, if you work frequently w/variables that may or may not
exist, and want to set default values if they don't exist,
dtml-set (an add-in) is great. You can say things like:

  <dtml-set varname="'Hello'" optional>

rather than the wordy

  <dtml-unless varname>
    <dtml-call "REQUEST.set('varname', 'Hello')">
  </dtml-unless>
 
Re: Don't need to predeclare to use in dtml-if by Wolfox - 2001-08-14
Uh... in fact I only did this because the following statement:

<dtml-if "send and not (name and emails and memo)">

failed with a NameError when send was not declared. Are you sure it should work? It didn't here.