web2pyTM Examples

Simple Examples

Here are some working and complete examples that explain the basic syntax of the framework.
You can click on the web2py keywords (in the highlighted code!) to get documentation.

Example 1

In controller: simple_examples.py
1.
2.
def hello1():
return "Hello World"

If the controller function returns a string, that is the body of the rendered page.
Try it here: hello1

Example 2

In controller: simple_examples.py
1.
2.
def hello2():
return T("Hello World")

The function T() marks strings that need to be translated. Translation dictionaries can be created at /admin/default/design
Try it here: hello2

Example 3

In controller: simple_examples.py
1.
2.
def hello3():
return dict(message=T("Hello World"))
and view: simple_examples/hello3.html
1.
2.
3.
4.
{{extend 'layout.html'}}
<h1>{{=message}}</h1>

If you return a dictionary, the variables defined in the dictionery are visible to the view (template).
Try it here: hello3

Actions can also be be rendered in other formsts like JSON, hello3.json, and XML, hello3.xml

Example 4

In controller: simple_examples.py
1.
2.
3.
def hello4():
response.view='simple_examples/hello3.html'
return dict(message=T("Hello World"))

You can change the view, but the default is /[controller]/[function].html. If the default is not found web2py tries to render the page using the generic.html view.
Try it here: hello4

Example 5

In controller: simple_examples.py
1.
2.
def hello5():
return HTML(BODY(H1(T('Hello World'),_style="color: red;"))).xml() # .xml to serialize

You can also generate HTML using helper objects HTML, BODY, H1, etc. Each of these tags is a class and the views know how to render the corresponding objects. The method .xml() serializes them and produce html/xml code for the page. Each tag, DIV for example, takes three types of arguments:

  • unnamed arguments, they correspond to nested tags
  • named arguments and name starts with '_'. These are mapped blindly into tag attributes and the '_' is removed. attributes without value like "READONLY" can be created with the argument "_readonly=ON".
  • named arguments and name does not start with '_'. They have a special meaning. See "value=" for INPUT, TEXTAREA, SELECT tags later.

Try it here: hello5

Example 6

In controller: simple_examples.py
1.
2.
3.
def hello6():
response.flash=T("Hello World in a flash!")
return dict(message=T("Hello World"))

response.flash allows you to flash a message to the user when the page is returned. Use session.flash instead of response.flash to display a message after redirection. With default layout, you can click on the flash to make it disappear.
Try it here: hello6

Example 7

In controller: simple_examples.py