Functions in views
Consider this “layout.html”:
<html>
<body>
{{include}}
<div class="sidebar">
{{if 'mysidebar' in globals():}}{{mysidebar()}}{{else:}}
my default sidebar
{{pass}}
</div>
</body>
</html>
and this extending view
{{def mysidebar():}}
my new sidebar!!!
{{return}}
{{extend 'layout.html'}}
Hello World!!!
Notice the function is defined before the {{extend...}}
statement — this results in the function being created before the “layout.html” code is executed, so the function can be called anywhere within “layout.html”, even before the {{include}}
. Also notice the function is included in the extended view without the =
prefix.
The code generates the following output:
<html>
<body>
Hello World!!!
<div class="sidebar">
my new sidebar!!!
</div>
</body>
</html>
Notice that the function is defined in HTML (although it could also contain Python code) so that response.write
is used to write its content (the function does not return the content). This is why the layout calls the view function using {{mysidebar()}}
rather than {{=mysidebar()}}
. Functions defined in this way can take arguments.