Question

I'm using Chameleon in Python to render my templates.

Let's say I want to populate a form field using POST/GET data:

<input type="text" name="foo" value="${request.params['foo']}" />

The problem with that is if request.params has no key "foo", I get an error. What's the simplest way to have value="" be empty if the key doesn't exist, rather than throwing an error?

Was it helpful?

Solution

request.params is a dict (or dict-like) object, so you can just use .get() with a default value:

<input type="text" name="foo" value="${request.params.get('foo', '')}" />

OTHER TIPS

What I ended up doing was extending request with a simple function:

def get_param(self, name):
    if name in self.params:
        return self.params[name]
    return None
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top