On Thursday, January 5, 2012 10:14:45 AM UTC-5, Peter O wrote:
>
> http://web2py.com/books/default/chapter/29/5?search=globals%28%29
The globals being accessed in the above linked example (which is actually
the 'welcome' app layout.html) are defined either in models or in another
(included) view, not in a controller.
> I see. Am I right that View doesn't see the global variables (in
> Controller), but the parent View sees the variables in View as global
> variables?
>
It depends. An extended view sees variables defined in an extending view if
(a) the variables are defined in the extending view before the {{extend}}
directive, or (b) the variables are referenced in the extended view after
the point where the extending view has been included. The sidebar example
in 'welcome' linked above works via (a). Note that /default/index.html in
'welcome' starts with:
{{left_sidebar_enabled,right_sidebar_enabled=False,True}}
{{extend 'layout.html'}}
By defining left_sidebar_enabled and right_sidebar_enabled before extending
layout.html, those variables are defined before any of the layout.html code
is executed, so they are available anywhere in layout.html (including
within any other views included within layout.html). When executing a view,
web2py first pieces together the entire page, with all extends and
includes, and then it executes the Python code to generate the HTML.
> Then, what causes the difference between Example 1 and 2? What's the
> relationship between the 'environment' and the 'context' in response? How
> do I access the 'environment' explicitly in the Controller?
>
In your second example, you have:
response.render('default/test.html', globals())
Passing globals() to response.render() adds all the globals to the
environment in which the view is rendered (actually, most of the objects in
globals() are already in the view environment, so you are only really
adding any new globals created in the controller). Your first example would
be equivalent to:
response.render('default/test.html', dict())
which is simply equivalent to:
response.render('default/test.html')
In that case, the view environment includes all the globals defined in the
models (as well as the web2py framework globals), but you haven't added any
variables generated in the controller to the view environment.
Anthony