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 1In controller: simple_examples.py
If the controller function returns a string, that is the body of the rendered page.
Try it here: hello1
Example 2In controller: simple_examples.py
The function T() marks strings that need to be translated. Translation dictionaries can be created at /admin/default/design
Try it here: hello2
Example 3In controller: simple_examples.py
If you return a dictionary, the variables defined in the dictionery are visible to the view (template).
Try it here: hello3
Example 4In controller: simple_examples.py
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 5In controller: simple_examples.py
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 6In controller: simple_examples.py
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