13.1 Placeholder Tips

Here's how to do certain important lookups that may not be obvious. For each, we show first the Cheetah expression and then the Python equivalent, because you can use these either in templates or in pure Python subclasses. The Cheetah examples use NameMapper shortcuts (uniform dotted notation, autocalling) as much as possible.

To verify whether a variable exists in the searchList:

$varExists('theVariable')
self.varExists('theVariable')
This is useful in #if or #unless constructs to avoid a #NameMapper.NotFound error if the variable doesn't exist. For instance, a CGI GET parameter that is normally supplied but in this case the user typed the URL by hand and forgot the parameter (or didn't know about it). (.hasVar is a synonym for .varExists.)

To look up a variable in the searchList from a Python method:

self.getVar('theVariable')
self.getVar('theVariable', myDefault)
This is the equivalent to $theVariable in the template. If the variable is missing, it returns the second argument, myDefault, if present, or raises NameMapper.NotFound if there is no second argument. However, it usually easier to write your method so that all needed searchList values come in as method arguments. That way the caller can just use a $placeholder to specify the argument, which is less verbose than you writing a getVar call.

To do a ``safe'' placeholder lookup that returns a default value if the variable is missing:

$getVar('theVariable', None)
$getVar('theVariable', $myDefault)

To get an environmental variable, put os.environ on the searchList as a container. Or read the envvar in Python code and set a placeholder variable for it.

Remember that variables found earlier in the searchList override same-name variables located in a later searchList object. Be careful when adding objects containing other variables besides the ones you want (e.g., os.environ, CGI parameters). The "other" variables may override variables your application depends on, leading to hard-to-find bugs. Also, users can inadvertently or maliciously set an environmental variable or CGI parameter you didn't expect, screwing up your program. To avoid all this, know what your namespaces contain, and place the namespaces you have the most control over first. For namespaces that could contain user-supplied "other" variables, don't put the namespace itself in the searchList; instead, copy the needed variables into your own "safe" namespace.