bottlepy / bottle

bottle.py is a fast and simple micro-framework for python web-applications.
http://bottlepy.org/
MIT License
8.44k stars 1.47k forks source link

Template function defined() doesn't work with dictionaries? #659

Open mjordan opened 10 years ago

mjordan commented 10 years ago

I'm running 0.12.7 and have hit a problem. I'm wondering if anyone can explain why the following code doesn't work if my_dict['id'] is defined in the current template:

% if defined(my_dict['id']):
    <input type="hidden" name="id" value="{{my_dict['id']}}" />
% end    

defined() is not returning True. I have confirmed that my_dict['id'] is getting passed to my template because I can output it in textfields in my form. If I replace my_dict['id'] with the name of a string variable, defined() does return True and the HTML is rendered as expected.

Possible bug, working as designed, or am I misunderstanding something?

avelino commented 10 years ago

defined read var, example:

defined('abc')

Recommend return you dict via args, example:

template('test.html', **my_dict)

In template:

% if defined('id'):
    <input type="hidden" name="id" value="{{ id }}" />
% end    

http://bottlepy.org/docs/dev/stpl.html#stpl.defined

mjordan commented 10 years ago

Thanks a million, that worked. But the docs at http://bottlepy.org/docs/0.12/tutorial.html#templates and http://bottlepy.org/docs/0.12/stpl.html don't provide examples of this type of usage. I don't mind opening a pull request to update the docs.

avelino commented 10 years ago

All contributions are welcome!

eric-wieser commented 10 years ago

Not sure that docs change makes sense - you're documenting a python language feature, not a bottle feature

mjordan commented 10 years ago

I'm documenting how to use a python language feature in a bottle template. Not sure why that doesn't make sense.

eric-wieser commented 9 years ago

Answering your original question:

% if 'id' in my_dict:
    <input type="hidden" name="id" value="{{my_dict['id']}}" />
% end
basbebe commented 9 years ago

@eric-wieser thanks, that was very helpful. I was totally lost since it seems that using the **ars method does not work with namespaces. My variables come from a .conf ini file with namespaces. However, the separator makes the variables not work. Using the "regular" approach solved that for me. Thanks!