Populating form fields using TAL/Chameleon
-
01-06-2021 - |
Pregunta
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?
Solución
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', '')}" />
Otros consejos
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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow