Conditional presence of a variable in view

436 views
Skip to first unread message

pepper_bg

unread,
Nov 9, 2011, 12:36:02 AM11/9/11
to web2py-users
I have a controller/view like these:

def control():
if some_condition():
return dict(form=form)
else:
return dict(form=form, table=get_table())

{{extend 'layout.html'}}
{{=form}}
{{if table:}}{{=table}}{{pass}}

i.e. 'form' is always present in the view and 'table' sometimes. The
{{if table:}}{{=table}}{{pass}}
condition doesn't seem to be working because when some_condition()
returns true I get:

Traceback (most recent call last):
File "/pub/web2py/gluon/restricted.py", line 194, in restricted
exec ccode in environment
File "/pub/web2py/applications/manage/views/default/control.html",
line 86, in <module>
NameError: name 'table' is not defined

I am missing something silly here. Actually believe this used to work.
Want to rule out view error before I look other places. Thanks for
your help!

Anthony

unread,
Nov 9, 2011, 1:34:10 AM11/9/11
to web...@googlegroups.com
No, that should never have worked. To do 'if table:', 'table' does have to be defined, and it will only be defined if passed from the controller. Here's what you can do:

{{if 'table' in globals():}}

or if there's a chance that when 'table' is actually returned it could be None/False/empty and you want to test for that, you could do:

{{if globals().get('table', False):}}

That will be False if 'table' does not exist, but still let you test for 'table' evaluating to False if it does exist.

You could also do 'return dict(form=form, table=None)' in that first condition of your controller, so 'table' will always be defined (again, assuming that the second condition would never return None as the value of 'table').

Anthony

pepper_bg

unread,
Nov 9, 2011, 2:38:34 AM11/9/11
to web2py-users
Appreciate it...
Reply all
Reply to author
Forward
0 new messages