------
+The first item in each list/tuple is the text to be displayed for the given menu item.
+
+The second item in each list/tuple is a boolean indicating whether that particular menu item is active
+(i.e., the currently selected item). When set to True, the MENU() helper will add a "web2py-menu-active"
+class to the <li> for that item (you can change the name of that class via the "li_active" argument to MENU
+()). Another way to specify the active url is by directly passing it to MENU() via its "active_url" argument.
+
The third item in each list/tuple can be an HTML helper (which could include nested helpers), and the ``MENU`` helper will simply render that helper rather than creating its own ``<a>`` tag.
------
------
The third item in each list/tuple can be an HTML helper (which could include nested helpers), and the ``MENU`` helper will simply render that helper rather than creating its own ``<a>`` tag.
------

+Self-closing tags can be generated with the TAG helper. The tag name must end with a "/".
+``
+{{=TAG['link/'](_href='http://web2py.com')}}
+``:code
+generates the following XML:
+``
+<link ref="http://web2py.com"/>
+``:code
Notice that ``TAG`` is an object, and ``TAG.name`` or ``TAG['name']`` is a function that returns a temporary helper class.
Notice that ``TAG`` is an object, and ``TAG.name`` or ``TAG['name']`` is a function that returns a temporary helper class.

Using the jQuery syntax "div#target" it is possible to specify multiple search criteria separated by a comma:
``
>>> a = DIV(SPAN('a', _id='t1'), DIV('b', _class='c2'))
>>> d = a.elements('span#t1, div.c2')
``:code
or equivalently
``
>>> a = DIV(SPAN('a', _id='t1'), DIV('b', _class='c2'))
>>> d = a.elements('span#t1', 'div.c2')
``:code
If the value of an attribute is specified using a name argument, it can be a string or a regular expression:
``
>>> a = DIV(SPAN('a', _id='test123'), DIV('b', _class='c2'))
>>> d = a.elements('span', _id=re.compile('test\d{3}')
``:code
A special named argument of the DIV (and derived) helpers is ``find``. It can be used to specify a search value or a search regular expression in the text content of the tag. For example:
``
>>> a = DIV(SPAN('abcde'), DIV('fghij'))
>>> d = a.elements(find='bcd')
>>> print d[0]
<span>abcde</span>
``:code
or
``
>>> a = DIV(SPAN('abcde'), DIV('fghij'))
>>> d = a.elements(find=re.compile('fg\w{3}'))
>>> print d[0]
<div>fghij</div>
``:code
+``components``:inxx
+#### ``components``
+
Here's an example of listing all elements in an html string:
``
html = TAG('<a>xxx</a><b>yyy</b>')
for item in html.components: print item
``:code
``parent``:inxx ``sibling``:inxx
#### ``parent`` and ``siblings``
``parent`` returns the parent of the current element.
``
>>> a = DIV(SPAN('a'),DIV('b'))
>>> s = a.element('span')
>>> d = s.parent
>>> d['_class']='abc'
>>> print a
<div class="abc"><span>a</span><div>b</div></div>
>>> for e in s.siblings(): print e
<div>b</div>
``:code
#### Replacing elements
Elements that are matched can also be replaced or removed by specifying
the ``replace`` argument. Notice that a
list of the original matching elements is still returned as usual.
``
list of the original matching elements is still returned as usual.
``replace`` can be a callable. In this case it will be passed
the original element and it is expected to return the replacement element:
``
>>> a = DIV(SPAN('x'), DIV(SPAN('y'))
>>> b = a.elements('span', replace=lambda t: P(t[0])
>>> print a
<div><p>x</p><div><p>y</p></div>
``:code
If ``replace=None``, matching elements will be removed completely.
``
>>> a = DIV(SPAN('x'), DIV(SPAN('y'))
>>> b = a.elements('span', replace=None)
>>> print a
<div></div>
``:code
+``flatten``:inxx
+#### ``flatten``
+
The flatten method recursively serializes the content of the children of a given element into regular text (without tags):
``
>>> a = DIV(SPAN('this', DIV('is', B('a'))), SPAN('test'))
>>> print a.flatten()
thisisatest
``:code
Flatten can be passed an optional argument, ``render``, i.e. a function that renders/flattens the content using a different protocol. Here is an example to serialize some tags into Markmin wiki syntax:
``
>>> a = DIV(H1('title'), P('example of a ', A('link', _href='#test')))
>>> from gluon.html import markmin_serializer
>>> print a.flatten(render=markmin_serializer)
# titles
example of [[a link #test]]
``:code
At the time of writing we provide ``markmin_serializer`` and ``markdown_serializer``.
#### Parsing
The TAG object is also an XML/HTML parser. It can read text and convert into a tree structure of helpers. This allows manipulation using the API above:
``
>>> html = '<h1>Title</h1><p>this is a <span>test</span></p>'
>>> parsed_html = TAG(html)
>>> parsed_html.element('span')[0]='TEST'
>>> print parsed_html
<h1>Title</h1><p>this is a <span>TEST</span></p>
``:code
``page layout``:inxx ``layout.html``:inxx ``extent``:inxx ``include``:inxx
+### Page layout
Views can extend and include other views in a tree-like structure.
For example, we can think of a view "index.html" that extends "layout.html" and includes "body.html".
At the same time, "layout.html" may include "header.html" and "footer.html".
The root of the tree is what we call a layout view. Just like any other HTML template file, you can edit it using the web2py administrative interface. The file name "layout.html" is just a convention.
Here is a minimalist page that extends the "layout.html" view and includes the "page.html" view:
``
{{extend 'layout.html'}}
<h1>Hello World</h1>
{{include 'page.html'}}
``:code
The extended layout file must contain an ``{{include}}`` directive, something like:
``
<html>
<head>
my new sidebar!!!
Hello World!!!
``:code
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>
``:code
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.
``block``:inxx
+### Blocks in views
Using the jQuery syntax "div#target" it is possible to specify multiple search criteria separated by a space:
``
>>> a = DIV(SPAN('a', _id='t1'), DIV('b', _class='c2'))
>>> d = a.elements('span#t1, div.c2')
``:code
or equivalently
``
>>> a = DIV(SPAN('a', _id='t1'), DIV('b', _class='c2'))
>>> d = a.elements('span#t1', 'div.c2')
``:code
If the value of an attribute is specified using a name argument, it can be a string or a regular expression:
``
>>> a = DIV(SPAN('a', _id='test123'), DIV('b', _class='c2'))
>>> d = a.elements('span', _id=re.compile('test\d{3}')
``:code
A special named argument of the DIV (and derived) helpers is ``find``. It can be used to specify a search value or a search regular expression in the text content of the tag. For example:
``
>>> a = DIV(SPAN('abcde'), DIV('fghij'))
>>> d = a.elements(find='bcd')
>>> print d[0]
<span>abcde</span>
``:code
or
``
>>> a = DIV(SPAN('abcde'), DIV('fghij'))
>>> d = a.elements(find=re.compile('fg\w{3}'))
>>> print d[0]
<div>fghij</div>
``:code
-#### ``components`` ``components``:inxx
Here's an example of listing all elements in an html string:
``
html = TAG('<a>xxx</a><b>yyy</b>')
for item in html.components: print item
``:code
``parent``:inxx ``sibling``:inxx
-
#### ``parent`` and ``siblings``
``parent`` returns the parent of the current element.
``
>>> a = DIV(SPAN('a'),DIV('b'))
>>> s = a.element('span')
>>> d = s.parent
>>> d['_class']='abc'
>>> print a
<div class="abc"><span>a</span><div>b</div></div>
>>> for e in s.siblings(): print e
<div>b</div>
``:code
#### Replacing elements
Elements that are matched can also be replaced or removed by specifying
the ``replace`` argument. Notice that a
list of the original matching elements is still returned as usual.
``
list of the original matching elements is still returned as usual.
``replace`` can be a callable. In this case it will be passed
the original element and it is expected to return the replacement element:
``
>>> a = DIV(SPAN('x'), DIV(SPAN('y'))
>>> b = a.elements('span', replace=lambda t: P(t[0])
>>> print a
<div><p>x</p><div><p>y</p></div>
``:code
If ``replace=None``, matching elements will be removed completely.
``
>>> a = DIV(SPAN('x'), DIV(SPAN('y'))
>>> b = a.elements('span', replace=None)
>>> print a
<div></div>
``:code
-#### ``flatten`` ``flatten``:inxx
The flatten method recursively serializes the content of the children of a given element into regular text (without tags):
``
>>> a = DIV(SPAN('this', DIV('is', B('a'))), SPAN('test'))
>>> print a.flatten()
thisisatest
``:code
Flatten can be passed an optional argument, ``render``, i.e. a function that renders/flattens the content using a different protocol. Here is an example to serialize some tags into Markmin wiki syntax:
``
>>> a = DIV(H1('title'), P('example of a ', A('link', _href='#test')))
>>> from gluon.html import markmin_serializer
>>> print a.flatten(render=markmin_serializer)
## titles
example of [[a link #test]]
``:code
At the time of writing we provide ``markmin_serializer`` and ``markdown_serializer``.
#### Parsing
The TAG object is also an XML/HTML parser. It can read text and convert into a tree structure of helpers. This allows manipulation using the API above:
``
>>> html = '<h1>Title</h1><p>this is a <span>test</span></p>'
>>> parsed_html = TAG(html)
>>> parsed_html.element('span')[0]='TEST'
>>> print parsed_html
<h1>Title</h1><p>this is a <span>TEST</span></p>
``:code
### Page layout
``page layout``:inxx ``layout.html``:inxx ``extent``:inxx ``include``:inxx
Views can extend and include other views in a tree-like structure.
For example, we can think of a view "index.html" that extends "layout.html" and includes "body.html".
At the same time, "layout.html" may include "header.html" and "footer.html".
The root of the tree is what we call a layout view. Just like any other HTML template file, you can edit it using the web2py administrative interface. The file name "layout.html" is just a convention.
Here is a minimalist page that extends the "layout.html" view and includes the "page.html" view:
``
{{extend 'layout.html'}}
<h1>Hello World</h1>
{{include 'page.html'}}
``:code
The extended layout file must contain an ``{{include}}`` directive, something like:
``
<html>
<head>
my new sidebar!!!
Hello World!!!
``:code
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>
``:code
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.
-### Blocks in views
``block``:inxx

and a click on the link causes the content to be loaded in the div. This is similar but more powerful than the above syntax since it is designed to refresh page components. We discuss applications of ``cid`` in more detail in [[Chapter 12 ../12#trapped_ajax_links]], in the context of components.
These ajax features require jQuery and "static/js/web2py_ajax.js", which are automatically included by placing ``{{include 'web2py_ajax.html'}}`` in the layout head. "views/web2py_ajax.html" defines some variables based on ``request`` and includes all necessary js and css files.
#### ``B``
``B``:inxx
This helper makes its contents bold.
``
>>> print B('<hello>', XML('<i>world</i>'), _class='test', _id=0)
<b id="0" class="test">&lt;hello&gt;<i>world</i></b>
``:code
#### ``BODY``
``BODY``:inxx
This helper makes the body of a page.
``
>>> print BODY('<hello>', XML('<b>world</b>'), _bgcolor='red')
<body bgcolor="red">&lt;hello&gt;<b>world</b></body>
``:code
Tags a table row. It should be rendered inside a table and contain ``<td>...</td
#### ``TT``
``TT``:inxx
Tags text as typewriter (monospaced) text.
``
>>> print TT('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<tt id="0" class="test">&lt;hello&gt;<b>world</b></tt>
``:code
#### ``UL``
Signifies an Unordered List and should contain LI items. If its content is not tagged as LI, UL does it automatically.
``UL``:inxx
``
>>> print UL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<ul id="0" class="test"><li>&lt;hello&gt;</li><li><b>world</b></li></ul>
``:code
+
+#### ``URL``
+The URL helper is documented in [[Chapter 4 URL ../04#URL]]
+
#### ``embed64``
and a click on the link causes the content to be loaded in the div. This is similar but more powerful than the above syntax since it is designed to refresh page components. We discuss applications of ``cid`` in more detail in Chapter 12, in the context of components.
These ajax features require jQuery and "static/js/web2py_ajax.js", which are automatically included by placing ``{{include 'web2py_ajax.html'}}`` in the layout head. "views/web2py_ajax.html" defines some variables based on ``request`` and includes all necessary js and css files.
#### ``B``
``B``:inxx
This helper makes its contents bold.
``
>>> print B('<hello>', XML('<i>world</i>'), _class='test', _id=0)
<b id="0" class="test">&lt;hello&gt;<i>world</i></b>
``:code
#### ``BODY``
``BODY``:inxx
This helper makes the body of a page.
``
>>> print BODY('<hello>', XML('<b>world</b>'), _bgcolor='red')
<body bgcolor="red">&lt;hello&gt;<b>world</b></body>
``:code
Tags a table row. It should be rendered inside a table and contain ``<td>...</td
#### ``TT``
``TT``:inxx
Tags text as typewriter (monospaced) text.
``
>>> print TT('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<tt id="0" class="test">&lt;hello&gt;<b>world</b></tt>
``:code
#### ``UL``
Signifies an Unordered List and should contain LI items. If its content is not tagged as LI, UL does it automatically.
``UL``:inxx
``
>>> print UL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<ul id="0" class="test"><li>&lt;hello&gt;</li><li><b>world</b></li></ul>
``:code
#### ``embed64``

+[[markmin_syntax]]
#### ``MARKMIN``
Implements the markmin wiki syntax. It converts the input text into output html according to the markmin rules described in the example below:
``MARKMIN``:inxx
``
>>> print MARKMIN("this is **bold** or ''italic'' and this [[a link http://web2py.com]]")
<p>this is <b>bold</b> or <i>italic</i> and
this <a href="http://web2py.com">a link</a></p>
``:code
The markmin syntax is described in this file that ships with web2py:
``
http://127.0.0.1:8000/examples/static/markmin.html
``:code
You can use markmin to generate HTML, LaTeX and PDF documents:
``
m = "Hello **world** [[link http://web2py.com]]"
Here is a basic syntax primer:
--------------------------------------------------
**SOURCE** | **OUTPUT**
``# title`` | **title**
``## section`` | **section**
``### subsection`` | **subsection**
``**bold**`` | **bold**
``''italic''`` | ''italic''
``!`!`verbatim`!`!`` | ``verbatim``
``http://google.com`` | http://google.com
``http://...`` | ``<a href="http://...">http:...</a>``
``http://...png`` | ``<img src="http://...png" />``
``http://...mp3`` | ``<audio src="http://...mp3"></audio>``
``http://...mp4`` | ``<video src="http://...mp4"></video>``
``qr:http://...`` | ``<a href="http://..."><img src="qr code"/></a>``
``embed:http://...`` | ``<iframe src="http://..."></iframe>``
``[[click me #myanchor]]`` | [[click me #myanchor]]
``[[myanchor]]`` | Creating an anchor for a link
``$````$\int_a^b sin(x)dx$````$`` | $$\int_a^b sin(x)dx$$
---------------------------------------------------
+##### MARKMIN links
+
+Links take this form: ``[[link display text <link>]]``
+<link> can be an anchor e.g. ``#myanchor``
+or a URI e.g. ``http://www.web2py.com``
+or a relative reference e.g. ``[[See Chapter 8 ../08]]`` or ``[[See Chapter 8 ../08#myanchor]]``
+
Simply including a link to an image, a videos or an audio files without markup result in the corresponding image, video or audio file being included automatically (for audio and video it uses html <audio> and <video> tags).
Adding a link with the ``qr:`` prefix such as
``
qr:http://web2py.com
``
results in the corresponding QR code being embedded and linking the said URL.
Adding a link with the ``embed:`` prefix such as
``
embed:http://www.youtube.com/embed/x1w8hKTJ2Co
``
results in the page being embedded, in this case a youtube video is embedded.
Images can also be embedded with the following syntax:
``
[[image-description http://.../image.png right 200px]]
``
+##### MARKMIN lists and tables
Unordered lists with:
``
- one
- two
- three
``
Ordered lists with:
``
+ one
+ two
+ three
``
and tables with:
``
----------
X | 0 | 0
0 | X | 0
0 | 0 | 1
----------
``
+##### extending MARKMIN
The MARKMIN syntax also supports blockquotes, HTML5 audio and video tags, image alignment, custom css, and it can be extended:
#### ``MARKMIN``
Implements the markmin wiki syntax. It converts the input text into output html according to the markmin rules described in the example below:
``MARKMIN``:inxx
``
>>> print MARKMIN("this is **bold** or ''italic'' and this [[a link http://web2py.com]]")
<p>this is <b>bold</b> or <i>italic</i> and
this <a href="http://web2py.com">a link</a></p>
``:code
The markmin syntax is described in this file that ships with web2py:
``
http://127.0.0.1:8000/examples/static/markmin.html
``:code
You can use markmin to generate HTML, LaTeX and PDF documents:
``
m = "Hello **world** [[link http://web2py.com]]"
Here is a basic syntax primer:
--------------------------------------------------
**SOURCE** | **OUTPUT**
``# title`` | **title**
``## section`` | **section**
``### subsection`` | **subsection**
``**bold**`` | **bold**
``''italic''`` | ''italic''
``!`!`verbatim`!`!`` | ``verbatim``
``http://google.com`` | http://google.com
``http://...`` | ``<a href="http://...">http:...</a>``
``http://...png`` | ``<img src="http://...png" />``
``http://...mp3`` | ``<audio src="http://...mp3"></audio>``
``http://...mp4`` | ``<video src="http://...mp4"></video>``
``qr:http://...`` | ``<a href="http://..."><img src="qr code"/></a>``
``embed:http://...`` | ``<iframe src="http://..."></iframe>``
``[[click me #myanchor]]`` | [[click me #myanchor]]
``[[myanchor]]`` | Creating an anchor for a link
``$````$\int_a^b sin(x)dx$````$`` | $$\int_a^b sin(x)dx$$
---------------------------------------------------
Simply including a link to an image, a videos or an audio files without markup result in the corresponding image, video or audio file being included automatically (for audio and video it uses html <audio> and <video> tags).
Adding a link with the ``qr:`` prefix such as
``
qr:http://web2py.com
``
results in the corresponding QR code being embedded and linking the said URL.
Adding a link with the ``embed:`` prefix such as
``
embed:http://www.youtube.com/embed/x1w8hKTJ2Co
``
results in the page being embedded, in this case a youtube video is embedded.
Images can also be embedded with the following syntax:
``
[[image-description http://.../image.png right 200px]]
``
Unordered lists with:
``
- one
- two
- three
``
Ordered lists with:
``
+ one
+ two
+ three
``
and tables with:
``
----------
X | 0 | 0
0 | X | 0
0 | 0 | 1
----------
``
The MARKMIN syntax also supports blockquotes, HTML5 audio and video tags, image alignment, custom css, and it can be extended:

+To understand how this works, consider apps based on the scaffolding app Welcome, which has a view layout.html. This view is included into the view ``default/index.html`` via ``{{extend 'layout.html'}}``. The contents of layout.html predefine certain blocks with certain default content, and these are therefore included into default/index.html.
+
+You can override these default content blocks by enclosing your new content inside the same block name. The location of the block in the layout.html is not changed, but the contents is.
+
+Here is a simplifed version. Imagine this is "layout.html":
``
<html>
<body>
{{include}}
<div class="sidebar">
{{block mysidebar}}
my default sidebar (this content to be replaced)
{{end}}
</div>
</body>
</html>
``:code
and this is a simple extending view ``default/index.html``:
``
{{extend 'layout.html'}}
Hello World!!!
{{block mysidebar}}
my new sidebar!!!
{{end}}
``:code
It generates the following output, where the content is provided by the over-riding block in the extending view, yet the enclosing DIV and class comes from layout.html. This allows consistency across views:
``
<html>
<body>
Hello World!!!
<div class="sidebar">
my new sidebar!!!
</div>
</body>
</html>
``:code
+The real layout.html defines a number of useful blocks, and you can easily add more to match the layout your desire.
+
You can have many blocks, and if a block is present in the extended view but not in the extending view, the content of the extended view is used. Also, notice that unlike with functions, it is not necessary to define blocks before the ``{{extend ...}}`` -- even if defined after the ``extend``, they can be used to make substitutions anywhere in the extended view.
-Consider this "layout.html":
``
<html>
<body>
{{include}}
<div class="sidebar">
{{block mysidebar}}
my default sidebar
{{end}}
</div>
</body>
</html>
``:code
and this extending view
``
{{extend 'layout.html'}}
Hello World!!!
{{block mysidebar}}
my new sidebar!!!
{{end}}
``:code
It generates the following output:
``
<html>
<body>
Hello World!!!
<div class="sidebar">
my new sidebar!!!
</div>
</body>
</html>
``:code
You can have many blocks, and if a block is present in the extended view but not in the extending view, the content of the extended view is used. Also, notice that unlike with functions, it is not necessary to define blocks before the ``{{extend ...}}`` -- even if defined after the ``extend``, they can be used to make substitutions anywhere in the extended view.

### Built-in helpers
#### ``A``
This helper is used to build links.
``A``:inxx
``
>>> print A('<click>', XML('<b>me</b>'),
_href='http://www.web2py.com')
<a href='http://www.web2py.com'>&lt;click&gt;<b>me/b></a>
``:code
Instead of ``_href`` you can pass the URL using the ``callback`` argument. For example in a view:
``
{{=A('click me', callback=URL('myaction'))}}
``
and the effect of pressing the link will be an ajax call to "myaction" instead of a redirection.
In this case, optionally you can specify two more arguments: ``target`` and ``delete``:
``
{{=A('click me', callback=URL('myaction'), target="t")}}
A typical application is:
``
{{=A('click me', callback=URL('myaction'), delete='tr")}}
``
in a table. Pressing the button will perform the callback and delete the table row.
``callback`` and ``delete`` can be combined.
The A helper takes a special argument called ``cid``. It works as follows:
``
{{=A('linked page', _href='http://example.com', cid='myid')}}
<div id="myid"></div>
``:code
and a click on the link causes the content to be loaded in the div. This is similar but more powerful than the above syntax since it is designed to refresh page components. We discuss applications of ``cid`` in more detail in Chapter 12, in the context of components.
These ajax features require jQuery and "static/js/web2py_ajax.js", which are automatically included by placing ``{{include 'web2py_ajax.html'}}`` in the layout head. "views/web2py_ajax.html" defines some variables based on ``request`` and includes all necessary js and css files.
#### ``B``
``B``:inxx
This helper makes its contents bold.
``
>>> print B('<hello>', XML('<i>world</i>'), _class='test', _id=0)
<b id="0" class="test">&lt;hello&gt;<i>world</i></b>
``:code
#### ``BODY``
``BODY``:inxx
This helper makes the body of a page.
``
>>> print BODY('<hello>', XML('<b>world</b>'), _bgcolor='red')
<body bgcolor="red">&lt;hello&gt;<b>world</b></body>
``:code
#### ``BR``
``BR``:inxx
This helper creates a line break.
``
>>> print BR()
<br />
``:code
Notice that helpers can be repeated using the multiplication operator:
``
>>> print BR()*5
<br /><br /><br /><br /><br />
``:code
#### ``CAT``
``CAT``:inxx
This helper concatenates other helpers, same as TAG[''].
``
>>> print CAT('Here is a ', A('link',_href=URL()), ', and here is some ', B('bold text'), '.')
Here is a <a href="/app/default/index">link</a>, and here is some <b>bold text</b>.
``:code
#### ``CENTER``
``CENTER``:inxx
This helper centers its content.
``
>>> print CENTER('<hello>', XML('<b>world</b>'),
>>> _class='test', _id=0)
<center id="0" class="test">&lt;hello&gt;<b>world</b></center>
``:code
#### ``CODE``
``CODE``:inxx
This helper performs syntax highlighting for Python, C, C++, HTML and web2py code, and is preferable to ``PRE`` for code listings. ``CODE`` also has the ability to create links to the web2py API documentation.
Here is an example of highlighting sections of Python code.
``
>>> print CODE('print "hello"', language='python').xml()
<table><tr valign="top"><td style="width:40px; text-align: right;"><pre style="
font-size: 11px;
font-family: Bitstream Vera Sans Mono,monospace;
background-color: transparent;
margin: 0;
padding: 5px;
border: none;
background-color: #E0E0E0;
color: #A0A0A0;
">1.</pre></td><td><pre style="
font-size: 11px;
font-family: Bitstream Vera Sans Mono,monospace;
background-color: transparent;
Here is a similar example for HTML
These are the default arguments for the ``CODE`` helper:
``
CODE("print 'hello world'", language='python', link=None, counter=1, styles={})
``:code
Supported values for the ``language`` argument are "python", "html_plain", "c", "cpp", "web2py", and "html". The "html" language interprets {{ and }} tags as "web2py" code, while "html_plain" doesn't.
If a ``link`` value is specified, for example "/examples/global/vars/", web2py API references in the code are linked to documentation at the link URL. For example "request" would be linked to "/examples/global/vars/request". In the above example, the link URL is handled by the "vars" action in the "global.py" controller that is distributed as part of the web2py "examples" application.
The ``counter`` argument is used for line numbering. It can be set to any of three different values. It can be ``None`` for no line numbers, a numerical value specifying the start number, or a string. If the counter is set to a string, it is interpreted as a prompt, and there are no line numbers.
The ``styles`` argument is a bit tricky. If you look at the generated HTML above, it contains a table with two columns, and each column has its own style declared inline using CSS. The ``styles`` attributes allows you to override those two CSS styles. For example:
``
{{=CODE(...,styles={'CODE':'margin: 0;padding: 5px;border: none;'})}}
``:code
The ``styles`` attribute must be a dictionary, and it allows two possible keys: ``CODE`` for the style of the actual code, and ``LINENUMBERS`` for the style of the left column, which contains the line numbers. Mind that these styles completely replace the default styles and are not simply added to them.
#### ``COL``
``COL``:inxx
``
>>> print COL('a','b')
<col>ab</col>
``:code
#### ``COLGROUP``
``COLGROUP``:inxx
``
>>> print COLGROUP('a','b')
<colgroup>ab</colgroup>
``:code
#### ``DIV``
All helpers apart from ``XML`` are derived from ``DIV`` and inherit its basic methods.
``DIV``:inxx
``
>>> print DIV('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<div id="0" class="test">&lt;hello&gt;<b>world</b></div>
``:code
#### ``EM``
Emphasizes its content.
``EM``:inxx
``
>>> print EM('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<em id="0" class="test">&lt;hello&gt;<b>world</b></em>
``:code
#### ``FIELDSET``
``FIELDSET``:inxx
This is used to create an input field together with its label.
``
>>> print FIELDSET('Height:', INPUT(_name='height'), _class='test')
<fieldset class="test">Height:<input name="height" /></fieldset>
``:code
#### ``FORM``
``FORM``:inxx
This is one of the most important helpers. In its simple form, it just makes a ``<form>...</form>`` tag, but because helpers are objects and have knowledge of what they contain, they can process submitted forms (for example, perform validation of the fields). This will be discussed in detail in Chapter 7.
``
>>> print FORM(INPUT(_type='submit'), _action='', _method='post')
<form enctype="multipart/form-data" action="" method="post">
<input type="submit" /></form>
``:code
The "enctype" is "multipart/form-data" by default.
``hidden``:inxx
The constructor of a ``FORM``, and of ``SQLFORM``, can also take a special argument called ``hidden``. When a dictionary is passed as ``hidden``, its items are translated into "hidden" INPUT fields. For example:
``
>>> print FORM(hidden=dict(a='b'))
<form enctype="multipart/form-data" action="" method="post">
<input value="b" type="hidden" name="a" /></form>
``:code
#### ``H1``, ``H2``, ``H3``, ``H4``, ``H5``, ``H6``
``H1``:inxx
These helpers are for paragraph headings and subheadings:
``
>>> print H1('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<h1 id="0" class="test">&lt;hello&gt;<b>world</b></h1>
``:code
#### ``HEAD``
For tagging the HEAD of an HTML page.
``HEAD``:inxx
``
>>> print HEAD(TITLE('<hello>', XML('<b>world</b>')))
<head><title>&lt;hello&gt;<b>world</b></title></head>
``:code
#### ``HTML``
``HTML``:inxx ``XHTML``:inxx
This helper is a little different. In addition to making the ``<html>`` tags,
it prepends the tag with a doctype string``xhtml-w,xhtml-o,xhtml-school``:cite .
``
>>> print HTML(BODY('<hello>', XML('<b>world</b>')))
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><body>&lt;hello&gt;<b>world</b></body></html>
``:code
The HTML helper also takes some additional optional arguments that have the following default:
``
HTML(..., lang='en', doctype='transitional')
``:code
where doctype can be 'strict', 'transitional', 'frameset', 'html5', or a full doctype string.
#### ``XHTML``
``XHTML``:inxx
XHTML is similar to HTML but it creates an XHTML doctype instead.
``
XHTML(..., lang='en', doctype='transitional', xmlns='http://www.w3.org/1999/xhtml')
``:code
where doctype can be 'strict', 'transitional', 'frameset', or a full doctype string.
#### ``HR``
``HR``:inxx
This helper creates a horizontal line in an HTML page
``
>>> print HR()
<hr />
``:code
#### ``I``
``I``:inxx
This helper makes its contents italic.
``
>>> print I('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<i id="0" class="test">&lt;hello&gt;<b>world</b></i>
``:code
#### ``IFRAME``
This helper includes another web page in the current page. The url of the other page is specified via the "_src" attribute.
``IFRAME``:inxx
``
>>> print IFRAME(_src='http://www.web2py.com')
<iframe src="http://www.web2py.com"></iframe>
``:code
#### ``IMG``
``IMG``:inxx
It can be used to embed images into HTML:
``
>>> IMG(_src='http://example.com/image.png',_alt='test')
<img src="http://example.com/image.ong" alt="rest" />
``:code
Here is a combination of A, IMG, and URL helpers for including a static image with a link:
``
>>> A(IMG(_src=URL('static','logo.png'), _alt="My Logo"),
_href=URL('default','index'))
<a href="/myapp/default/index">
<img src="/myapp/static/logo.png" alt="My Logo" />
</a>
``:code
#### ``INPUT``
``INPUT``:inxx
Creates an ``<input.../>`` tag. An input tag may not contain other tags, and is closed by ``/>`` instead of ``>``. The input tag has an optional attribute ``_type`` that can be set to "text" (the default), "submit", "checkbox", or "radio".
``
>>> print INPUT(_name='test', _value='a')
<input value="a" name="test" />
``:code
It also takes an optional special argument called "value", distinct from "_value". The latter sets the default value for the input field; the former sets its current value. For an input of type "text", the former overrides the latter:
``
>>> print INPUT(_name='test', _value='a', value='b')
<input value="b" name="test" />
``:code
For radio buttons, ``INPUT`` selectively sets the "checked" attribute:
``radio``:inxx
``
>>> for v in ['a', 'b', 'c']:
>>> print INPUT(_type='radio', _name='test', _value=v, value='b'), v
<input value="a" type="radio" name="test" /> a
<input value="b" type="radio" checked="checked" name="test" /> b
<input value="c" type="radio" name="test" /> c
``:code
and similarly for checkboxes:
``checkbox``:inxx
``
>>> print INPUT(_type='checkbox', _name='test', _value='a', value=True)
<input value="a" type="checkbox" checked="checked" name="test" />
>>> print INPUT(_type='checkbox', _name='test', _value='a', value=False)
<input value="a" type="checkbox" name="test" />
``:code
#### ``LABEL``
It is used to create a LABEL tag for an INPUT field.
``LABEL``:inxx
``
>>> print LABEL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<label id="0" class="test">&lt;hello&gt;<b>world</b></label>
``:code
#### ``LEGEND``
It is used to create a legend tag for a field in a form.
``LEGEND``:inxx
``
>>> print LEGEND('Name', _for='myfield')
<legend for="myfield">Name</legend>
``:code
#### ``LI``
It makes a list item and should be contained in a ``UL`` or ``OL`` tag.
``LI``:inxx
``
>>> print LI('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<li id="0" class="test">&lt;hello&gt;<b>world</b></li>
``:code
#### ``META``
To be used for building ``META`` tags in the ``HTML`` head. For example:
``META``:inxx
``
>>> print META(_name='security', _content='high')
<meta name="security" content="high" />
``:code
#### ``MARKMIN``
Implements the markmin wiki syntax. It converts the input text into output html according to the markmin rules described in the example below:
``MARKMIN``:inxx
``
>>> print MARKMIN("this is **bold** or ''italic'' and this [[a link http://web2py.com]]")
<p>this is <b>bold</b> or <i>italic</i> and
this <a href="http://web2py.com">a link</a></p>
``:code
The markmin syntax is described in this file that ships with web2py:
``
http://127.0.0.1:8000/examples/static/markmin.html
``:code
You can use markmin to generate HTML, LaTeX and PDF documents:
``
m = "Hello **world** [[link http://web2py.com]]"
from gluon.contrib.markmin.markmin2html import markmin2html
print markmin2pdf(m) # requires pdflatex
(the ``MARKMIN`` helper is a shortcut for ``markmin2html``)
Here is a basic syntax primer:
--------------------------------------------------
**SOURCE** | **OUTPUT**
``# title`` | **title**
``## section`` | **section**
``### subsection`` | **subsection**
``**bold**`` | **bold**
``''italic''`` | ''italic''
``!`!`verbatim`!`!`` | ``verbatim``
``http://google.com`` | http://google.com
``http://...`` | ``<a href="http://...">http:...</a>``
``http://...png`` | ``<img src="http://...png" />``
``http://...mp3`` | ``<audio src="http://...mp3"></audio>``
``http://...mp4`` | ``<video src="http://...mp4"></video>``
``qr:http://...`` | ``<a href="http://..."><img src="qr code"/></a>``
``embed:http://...`` | ``<iframe src="http://..."></iframe>``
``[[click me #myanchor]]`` | [[click me #myanchor]]
+``[[myanchor]]`` | Creating an anchor for a link
``$````$\int_a^b sin(x)dx$````$`` | $$\int_a^b sin(x)dx$$
---------------------------------------------------
Simply including a link to an image, a videos or an audio files without markup result in the corresponding image, video or audio file being included automatically (for audio and video it uses html <audio> and <video> tags).
Adding a link with the ``qr:`` prefix such as
``
qr:http://web2py.com
``
results in the corresponding QR code being embedded and linking the said URL.
Adding a link with the ``embed:`` prefix such as
``
embed:http://www.youtube.com/embed/x1w8hKTJ2Co
``
results in the page being embedded, in this case a youtube video is embedded.
and tables with:
``
----------
X | 0 | 0
0 | X | 0
0 | 0 | 1
----------
``
The MARKMIN syntax also supports blockquotes, HTML5 audio and video tags, image alignment, custom css, and it can be extended:
``
MARKMIN("!`!!`!abab!`!!`!:custom", extra=dict(custom=lambda text: text.replace('a','c'))
``:code
generates
``'cbcb'``:code
Custom blocks are delimited by ``!`!!`!...!`!!`!:<key>`` and they are rendered by the function passed as value for the corresponding key in the extra dictionary argument of MARKMIN. Mind that the function may need to escape the output to prevent XSS.
#### ``OBJECT``
Used to embed objects (for example, a flash player) in the HTML.
``OBJECT``:inxx
``
>>> print OBJECT('<hello>', XML('<b>world</b>'),
>>> _src='http://www.web2py.com')
<object src="http://www.web2py.com">&lt;hello&gt;<b>world</b></object>
``:code
#### ``OL``
It stands for Ordered List. The list should contain LI tags. ``OL`` arguments that are not ``LI`` objects are automatically enclosed in ``<li>...</li>`` tags.
``OL``:inxx
``
>>> print OL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<ol id="0" class="test"><li>&lt;hello&gt;</li><li><b>world</b></li></ol>
``:code
#### ``ON``
This is here for backward compatibility and it is simply an alias for ``True``. It is used exclusively for checkboxes and deprecated since ``True`` is more Pythonic.
``ON``:inxx
``
>>> print INPUT(_type='checkbox', _name='test', _checked=ON)
<input checked="checked" type="checkbox" name="test" />
``:code
#### ``OPTGROUP``
Allows you to group multiple options in a SELECT and it is useful to customize the fields using CSS.
``OPTGROUP``:inxx
``
>>> print SELECT('a', OPTGROUP('b', 'c'))
<select>
<option value="a">a</option>
<optgroup>
<option value="b">b</option>
<option value="c">c</option>
</optgroup>
</select>
``:code
#### ``OPTION``
This should only be used as part of a SELECT/OPTION combination.
``OPTION``:inxx
``
>>> print OPTION('<hello>', XML('<b>world</b>'), _value='a')
<option value="a">&lt;hello&gt;<b>world</b></option>
``:code
As in the case of ``INPUT``, web2py make a distinction between "_value" (the value of the OPTION), and "value" (the current value of the enclosing select). If they are equal, the option is "selected".
``selected``:inxx
``
>>> print SELECT('a', 'b', value='b'):
<select>
<option value="a">a</option>
<option value="b" selected="selected">b</option>
</select>
``:code
#### ``P``
``P``:inxx
This is for tagging a paragraph.
``
>>> print P('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<p id="0" class="test">&lt;hello&gt;<b>world</b></p>
``:code
#### ``PRE``
``PRE``:inxx
Generates a ``<pre>...</pre>`` tag for displaying pre-formatted text. The ``CODE`` helper is generally preferable for code listings.
``
>>> print PRE('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<pre id="0" class="test">&lt;hello&gt;<b>world</b></pre>
``:code
#### ``SCRIPT``
``SCRIPT``:inxx
This is include or link a script, such as JavaScript. The content between the tags is rendered as an HTML comment, for the benefit of really old browsers.
``
>>> print SCRIPT('alert("hello world");', _type='text/javascript')
<script type="text/javascript"><!--
alert("hello world");
//--></script>
``:code
#### ``SELECT``
``SELECT``:inxx
Makes a ``<select>...</select>`` tag. This is used with the ``OPTION`` helper. Those ``SELECT`` arguments that are not ``OPTION`` objects are automatically converted to options.
``
>>> print SELECT('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<select id="0" class="test">
<option value="&lt;hello&gt;">&lt;hello&gt;</option>
<option value="&lt;b&gt;world&lt;/b&gt;"><b>world</b></option>
</select>
``:code
#### ``SPAN``
``SPAN``:inxx
Similar to ``DIV`` but used to tag inline (rather than block) content.
``
>>> print SPAN('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<span id="0" class="test">&lt;hello&gt;<b>world</b></span>
``:code
#### ``STYLE``
``STYLE``:inxx
Similar to script, but used to either include or link CSS code.
Here the CSS is included:
``
>>> print STYLE(XML('body {color: white}'))
<style><!--
body { color: white }
//--></style>
``:code
and here it is linked:
``
>>> print STYLE(_src='style.css')
<style src="style.css"><!--
//--></style>
``:code
#### ``TABLE``, ``TR``, ``TD``
``TABLE``:inxx ``TR``:inxx ``TD``:inxx
These tags (along with the optional ``THEAD``, ``TBODY`` and ``TFOOTER`` helpers) are used to build HTML tables.
``
>>> print TABLE(TR(TD('a'), TD('b')), TR(TD('c'), TD('d')))
<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>
``:code
``TR`` expects ``TD`` content; arguments that are not ``TD`` objects are converted automatically.
``
>>> print TABLE(TR('a', 'b'), TR('c', 'd'))
<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>
``:code
It is easy to convert a Python array into an HTML table using Python's ``*`` function arguments notation, which maps list elements to positional function arguments.
Here, we will do it line by line:
``
>>> table = [['a', 'b'], ['c', 'd']]
>>> print TABLE(TR(*table[0]), TR(*table[1]))
<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>
``:code
Here we do all lines at once:
``
>>> table = [['a', 'b'], ['c', 'd']]
>>> print TABLE(*[TR(*rows) for rows in table])
<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>
``:code
#### ``TBODY``
``TBODY``:inxx
This is used to tag rows contained in the table body, as opposed to header or footer rows. It is optional.
``
>>> print TBODY(TR('<hello>'), _class='test', _id=0)
<tbody id="0" class="test"><tr><td>&lt;hello&gt;</td></tr></tbody>
``:code
#### ``TEXTAREA``
``TEXTAREA``:inxx
This helper makes a ``<textarea>...</textarea>`` tag.
``
>>> print TEXTAREA('<hello>', XML('<b>world</b>'), _class='test')
<textarea class="test" cols="40" rows="10">&lt;hello&gt;<b>world</b></textarea>
``:code
The only caveat is that its optional "value" overrides its content (inner HTML)
``
>>> print TEXTAREA(value="<hello world>", _class="test")
<textarea class="test" cols="40" rows="10">&lt;hello world&gt;</textarea>
``:code
#### ``TFOOT``
``TFOOT``:inxx
This is used to tag table footer rows.
``
>>> print TFOOT(TR(TD('<hello>')), _class='test', _id=0)
<tfoot id="0" class="test"><tr><td>&lt;hello&gt;</td></tr></tfoot>
``:code
#### ``TH``
``TH``:inxx
This is used instead of ``TD`` in table headers.
``
>>> print TH('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<th id="0" class="test">&lt;hello&gt;<b>world</b></th>
``:code
#### ``THEAD``
``THEAD``:inxx
This is used to tag table header rows.
``
>>> print THEAD(TR(TH('<hello>')), _class='test', _id=0)
<thead id="0" class="test"><tr><th>&lt;hello&gt;</th></tr></thead>
``:code
#### ``TITLE``
``TITLE``:inxx
This is used to tag the title of a page in an HTML header.
``
>>> print TITLE('<hello>', XML('<b>world</b>'))
<title>&lt;hello&gt;<b>world</b></title>
``:code
#### ``TR``
``TR``:inxx
Tags a table row. It should be rendered inside a table and contain ``<td>...</td>`` tags. ``TR`` arguments that are not ``TD`` objects will be automatically converted.
``
>>> print TR('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<tr id="0" class="test"><td>&lt;hello&gt;</td><td><b>world</b></td></tr>
``:code
#### ``TT``
``TT``:inxx
Tags text as typewriter (monospaced) text.
``
>>> print TT('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<tt id="0" class="test">&lt;hello&gt;<b>world</b></tt>
``:code
#### ``UL``
Signifies an Unordered List and should contain LI items. If its content is not tagged as LI, UL does it automatically.
``UL``:inxx
``
>>> print UL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<ul id="0" class="test"><li>&lt;hello&gt;</li><li><b>world</b></li></ul>
``:code
#### ``embed64``
``embed64(filename=None, file=None, data=None, extension='image/gif')`` encodes the provided (binary) data into base64.
filename: if provided, opens and reads this file in 'rb' mode.
file: if provided, reads this file.
data: if provided, uses the provided data.
``embed64``:inxx
#### ``xmlescape``
``xmlescape(data, quote=True)`` returns an escaped string of the provided data.
``xmlescape``:inxx
``
>>> print xmlescape('<hello>')
&lt;hello&gt;
``:code
### Custom helpers
#### ``TAG``
``TAG``:inxx
Sometimes you need to generate custom XML tags. web2py provides ``TAG``, a universal tag generator.
``
{{=TAG.name('a', 'b', _c='d')}}
``:code
generates the following XML
``
<name c="d">ab</name>
``:code
Arguments "a", "b", and "d" are automatically escaped; use the ``XML`` helper to suppress this behavior. Using ``TAG`` you can generate HTML/XML tags not already provided by the API. TAGs can be nested, and are serialized with ``str().``
An equivalent syntax is:
``
{{=TAG['name']('a', 'b', c='d')}}
``:code
If the TAG object is created with an empty name, it can be used to concatenate multiple strings and HTML helpers together without inserting them into a surrounding tag, but this use is deprecated. Use the ``CAT`` helper instead.
Notice that ``TAG`` is an object, and ``TAG.name`` or ``TAG['name']`` is a function that returns a temporary helper class.
#### ``MENU``
``MENU``:inxx
#### Built-in helpers
##### ``A``
This helper is used to build links.
``A``:inxx
``
>>> print A('<click>', XML('<b>me</b>'),
_href='http://www.web2py.com')
<a href='http://www.web2py.com'>&lt;click&gt;<b>me/b></a>
``:code
Instead of ``_href`` you can pass the URL using the ``callback`` argument. For example in a view:
``
{{=A('click me', callback=URL('myaction'))}}
``
and the effect of pressing the link will be an ajax call to "myaction" instead of a redirection.
In this case, optionally you can specify two more arguments: ``target`` and ``delete``:
``
{{=A('click me', callback=URL('myaction'), target="t")}}
A typical application is:
``
{{=A('click me', callback=URL('myaction'), delete='tr")}}
``
in a table. Pressing the button will perform the callback and delete the table row.
``callback`` and ``delete`` can be combined.
The A helper takes a special argument called ``cid``. It works as follows:
``
{{=A('linked page', _href='http://example.com', cid='myid')}}
<div id="myid"></div>
``:code
and a click on the link causes the content to be loaded in the div. This is similar but more powerful than the above syntax since it is designed to refresh page components. We discuss applications of ``cid`` in more detail in Chapter 12, in the context of components.
These ajax features require jQuery and "static/js/web2py_ajax.js", which are automatically included by placing ``{{include 'web2py_ajax.html'}}`` in the layout head. "views/web2py_ajax.html" defines some variables based on ``request`` and includes all necessary js and css files.
##### ``B``
``B``:inxx
This helper makes its contents bold.
``
>>> print B('<hello>', XML('<i>world</i>'), _class='test', _id=0)
<b id="0" class="test">&lt;hello&gt;<i>world</i></b>
``:code
##### ``BODY``
``BODY``:inxx
This helper makes the body of a page.
``
>>> print BODY('<hello>', XML('<b>world</b>'), _bgcolor='red')
<body bgcolor="red">&lt;hello&gt;<b>world</b></body>
``:code
##### ``BR``
``BR``:inxx
This helper creates a line break.
``
>>> print BR()
<br />
``:code
Notice that helpers can be repeated using the multiplication operator:
``
>>> print BR()*5
<br /><br /><br /><br /><br />
``:code
##### ``CAT``
``CAT``:inxx
This helper concatenates other helpers, same as TAG[''].
``
>>> print CAT('Here is a ', A('link',_href=URL()), ', and here is some ', B('bold text'), '.')
Here is a <a href="/app/default/index">link</a>, and here is some <b>bold text</b>.
``:code
##### ``CENTER``
``CENTER``:inxx
This helper centers its content.
``
>>> print CENTER('<hello>', XML('<b>world</b>'),
>>> _class='test', _id=0)
<center id="0" class="test">&lt;hello&gt;<b>world</b></center>
``:code
##### ``CODE``
``CODE``:inxx
This helper performs syntax highlighting for Python, C, C++, HTML and web2py code, and is preferable to ``PRE`` for code listings. ``CODE`` also has the ability to create links to the web2py API documentation.
Here is an example of highlighting sections of Python code.
``
>>> print CODE('print "hello"', language='python').xml()
<table><tr valign="top"><td style="width:40px; text-align: right;"><pre style="
font-size: 11px;
font-family: Bitstream Vera Sans Mono,monospace;
background-color: transparent;
margin: 0;
padding: 5px;
border: none;
background-color: #E0E0E0;
color: #A0A0A0;
">1.</pre></td><td><pre style="
font-size: 11px;
font-family: Bitstream Vera Sans Mono,monospace;
background-color: transparent;
Here is a similar example for HTML
These are the default arguments for the ``CODE`` helper:
``
CODE("print 'hello world'", language='python', link=None, counter=1, styles={})
``:code
Supported values for the ``language`` argument are "python", "html_plain", "c", "cpp", "web2py", and "html". The "html" language interprets {{ and }} tags as "web2py" code, while "html_plain" doesn't.
If a ``link`` value is specified, for example "/examples/global/vars/", web2py API references in the code are linked to documentation at the link URL. For example "request" would be linked to "/examples/global/vars/request". In the above example, the link URL is handled by the "vars" action in the "global.py" controller that is distributed as part of the web2py "examples" application.
The ``counter`` argument is used for line numbering. It can be set to any of three different values. It can be ``None`` for no line numbers, a numerical value specifying the start number, or a string. If the counter is set to a string, it is interpreted as a prompt, and there are no line numbers.
The ``styles`` argument is a bit tricky. If you look at the generated HTML above, it contains a table with two columns, and each column has its own style declared inline using CSS. The ``styles`` attributes allows you to override those two CSS styles. For example:
``
{{=CODE(...,styles={'CODE':'margin: 0;padding: 5px;border: none;'})}}
``:code
The ``styles`` attribute must be a dictionary, and it allows two possible keys: ``CODE`` for the style of the actual code, and ``LINENUMBERS`` for the style of the left column, which contains the line numbers. Mind that these styles completely replace the default styles and are not simply added to them.
##### ``COL``
``COL``:inxx
``
>>> print COL('a','b')
<col>ab</col>
``:code
##### ``COLGROUP``
``COLGROUP``:inxx
``
>>> print COLGROUP('a','b')
<colgroup>ab</colgroup>
``:code
##### ``DIV``
All helpers apart from ``XML`` are derived from ``DIV`` and inherit its basic methods.
``DIV``:inxx
``
>>> print DIV('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<div id="0" class="test">&lt;hello&gt;<b>world</b></div>
``:code
##### ``EM``
Emphasizes its content.
``EM``:inxx
``
>>> print EM('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<em id="0" class="test">&lt;hello&gt;<b>world</b></em>
``:code
##### ``FIELDSET``
``FIELDSET``:inxx
This is used to create an input field together with its label.
``
>>> print FIELDSET('Height:', INPUT(_name='height'), _class='test')
<fieldset class="test">Height:<input name="height" /></fieldset>
``:code
##### ``FORM``
``FORM``:inxx
This is one of the most important helpers. In its simple form, it just makes a ``<form>...</form>`` tag, but because helpers are objects and have knowledge of what they contain, they can process submitted forms (for example, perform validation of the fields). This will be discussed in detail in Chapter 7.
``
>>> print FORM(INPUT(_type='submit'), _action='', _method='post')
<form enctype="multipart/form-data" action="" method="post">
<input type="submit" /></form>
``:code
The "enctype" is "multipart/form-data" by default.
``hidden``:inxx
The constructor of a ``FORM``, and of ``SQLFORM``, can also take a special argument called ``hidden``. When a dictionary is passed as ``hidden``, its items are translated into "hidden" INPUT fields. For example:
``
>>> print FORM(hidden=dict(a='b'))
<form enctype="multipart/form-data" action="" method="post">
<input value="b" type="hidden" name="a" /></form>
``:code
##### ``H1``, ``H2``, ``H3``, ``H4``, ``H5``, ``H6``
``H1``:inxx
These helpers are for paragraph headings and subheadings:
``
>>> print H1('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<h1 id="0" class="test">&lt;hello&gt;<b>world</b></h1>
``:code
##### ``HEAD``
For tagging the HEAD of an HTML page.
``HEAD``:inxx
``
>>> print HEAD(TITLE('<hello>', XML('<b>world</b>')))
<head><title>&lt;hello&gt;<b>world</b></title></head>
``:code
##### ``HTML``
``HTML``:inxx ``XHTML``:inxx
This helper is a little different. In addition to making the ``<html>`` tags,
it prepends the tag with a doctype string``xhtml-w,xhtml-o,xhtml-school``:cite .
``
>>> print HTML(BODY('<hello>', XML('<b>world</b>')))
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><body>&lt;hello&gt;<b>world</b></body></html>
``:code
The HTML helper also takes some additional optional arguments that have the following default:
``
HTML(..., lang='en', doctype='transitional')
``:code
where doctype can be 'strict', 'transitional', 'frameset', 'html5', or a full doctype string.
##### ``XHTML``
``XHTML``:inxx
XHTML is similar to HTML but it creates an XHTML doctype instead.
``
XHTML(..., lang='en', doctype='transitional', xmlns='http://www.w3.org/1999/xhtml')
``:code
where doctype can be 'strict', 'transitional', 'frameset', or a full doctype string.
##### ``HR``
``HR``:inxx
This helper creates a horizontal line in an HTML page
``
>>> print HR()
<hr />
``:code
##### ``I``
``I``:inxx
This helper makes its contents italic.
``
>>> print I('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<i id="0" class="test">&lt;hello&gt;<b>world</b></i>
``:code
##### ``IFRAME``
This helper includes another web page in the current page. The url of the other page is specified via the "_src" attribute.
``IFRAME``:inxx
``
>>> print IFRAME(_src='http://www.web2py.com')
<iframe src="http://www.web2py.com"></iframe>
``:code
##### ``IMG``
``IMG``:inxx
It can be used to embed images into HTML:
``
>>> IMG(_src='http://example.com/image.png',_alt='test')
<img src="http://example.com/image.ong" alt="rest" />
``:code
Here is a combination of A, IMG, and URL helpers for including a static image with a link:
``
>>> A(IMG(_src=URL('static','logo.png'), _alt="My Logo"),
_href=URL('default','index'))
<a href="/myapp/default/index">
<img src="/myapp/static/logo.png" alt="My Logo" />
</a>
``:code
##### ``INPUT``
``INPUT``:inxx
Creates an ``<input.../>`` tag. An input tag may not contain other tags, and is closed by ``/>`` instead of ``>``. The input tag has an optional attribute ``_type`` that can be set to "text" (the default), "submit", "checkbox", or "radio".
``
>>> print INPUT(_name='test', _value='a')
<input value="a" name="test" />
``:code
It also takes an optional special argument called "value", distinct from "_value". The latter sets the default value for the input field; the former sets its current value. For an input of type "text", the former overrides the latter:
``
>>> print INPUT(_name='test', _value='a', value='b')
<input value="b" name="test" />
``:code
For radio buttons, ``INPUT`` selectively sets the "checked" attribute:
``radio``:inxx
``
>>> for v in ['a', 'b', 'c']:
>>> print INPUT(_type='radio', _name='test', _value=v, value='b'), v
<input value="a" type="radio" name="test" /> a
<input value="b" type="radio" checked="checked" name="test" /> b
<input value="c" type="radio" name="test" /> c
``:code
and similarly for checkboxes:
``checkbox``:inxx
``
>>> print INPUT(_type='checkbox', _name='test', _value='a', value=True)
<input value="a" type="checkbox" checked="checked" name="test" />
>>> print INPUT(_type='checkbox', _name='test', _value='a', value=False)
<input value="a" type="checkbox" name="test" />
``:code
##### ``LABEL``
It is used to create a LABEL tag for an INPUT field.
``LABEL``:inxx
``
>>> print LABEL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<label id="0" class="test">&lt;hello&gt;<b>world</b></label>
``:code
##### ``LEGEND``
It is used to create a legend tag for a field in a form.
``LEGEND``:inxx
``
>>> print LEGEND('Name', _for='myfield')
<legend for="myfield">Name</legend>
``:code
##### ``LI``
It makes a list item and should be contained in a ``UL`` or ``OL`` tag.
``LI``:inxx
``
>>> print LI('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<li id="0" class="test">&lt;hello&gt;<b>world</b></li>
``:code
##### ``META``
To be used for building ``META`` tags in the ``HTML`` head. For example:
``META``:inxx
``
>>> print META(_name='security', _content='high')
<meta name="security" content="high" />
``:code
##### ``MARKMIN``
Implements the markmin wiki syntax. It converts the input text into output html according to the markmin rules described in the example below:
``MARKMIN``:inxx
``
>>> print MARKMIN("this is **bold** or ''italic'' and this [[a link http://web2py.com]]")
<p>this is <b>bold</b> or <i>italic</i> and
this <a href="http://web2py.com">a link</a></p>
``:code
The markmin syntax is described in this file that ships with web2py:
``
http://127.0.0.1:8000/examples/static/markmin.html
``:code
You can use markmin to generate HTML, LaTeX and PDF documents:
``
m = "Hello **world** [[link http://web2py.com]]"
from gluon.contrib.markmin.markmin2html import markmin2html
print markmin2pdf(m) # requires pdflatex
(the ``MARKMIN`` helper is a shortcut for ``markmin2html``)
Here is a basic syntax primer:
--------------------------------------------------
**SOURCE** | **OUTPUT**
``# title`` | **title**
``## section`` | **section**
``### subsection`` | **subsection**
``**bold**`` | **bold**
``''italic''`` | ''italic''
``!`!`verbatim`!`!`` | ``verbatim``
``http://google.com`` | http://google.com
``http://...`` | ``<a href="http://...">http:...</a>``
``http://...png`` | ``<img src="http://...png" />``
``http://...mp3`` | ``<audio src="http://...mp3"></audio>``
``http://...mp4`` | ``<video src="http://...mp4"></video>``
``qr:http://...`` | ``<a href="http://..."><img src="qr code"/></a>``
``embed:http://...`` | ``<iframe src="http://..."></iframe>``
``[[click me #myanchor]]`` | [[click me #myanchor]]
``$````$\int_a^b sin(x)dx$````$`` | $$\int_a^b sin(x)dx$$
---------------------------------------------------
Simply including a link to an image, a videos or an audio files without markup result in the corresponding image, video or audio file being included automatically (for audio and video it uses html <audio> and <video> tags).
Adding a link with the ``qr:`` prefix such as
``
qr:http://web2py.com
``
results in the corresponding QR code being embedded and linking the said URL.
Adding a link with the ``embed:`` prefix such as
``
embed:http://www.youtube.com/embed/x1w8hKTJ2Co
``
results in the page being embedded, in this case a youtube video is embedded.
and tables with:
``
----------
X | 0 | 0
0 | X | 0
0 | 0 | 1
----------
``
The MARKMIN syntax also supports blockquotes, HTML5 audio and video tags, image alignment, custom css, and it can be extended:
``
MARKMIN("!`!!`!abab!`!!`!:custom", extra=dict(custom=lambda text: text.replace('a','c'))
``:code
generates
``'cbcb'``:code
Custom blocks are delimited by ``!`!!`!...!`!!`!:<key>`` and they are rendered by the function passed as value for the corresponding key in the extra dictionary argument of MARKMIN. Mind that the function may need to escape the output to prevent XSS.
##### ``OBJECT``
Used to embed objects (for example, a flash player) in the HTML.
``OBJECT``:inxx
``
>>> print OBJECT('<hello>', XML('<b>world</b>'),
>>> _src='http://www.web2py.com')
<object src="http://www.web2py.com">&lt;hello&gt;<b>world</b></object>
``:code
##### ``OL``
It stands for Ordered List. The list should contain LI tags. ``OL`` arguments that are not ``LI`` objects are automatically enclosed in ``<li>...</li>`` tags.
``OL``:inxx
``
>>> print OL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<ol id="0" class="test"><li>&lt;hello&gt;</li><li><b>world</b></li></ol>
``:code
##### ``ON``
This is here for backward compatibility and it is simply an alias for ``True``. It is used exclusively for checkboxes and deprecated since ``True`` is more Pythonic.
``ON``:inxx
``
>>> print INPUT(_type='checkbox', _name='test', _checked=ON)
<input checked="checked" type="checkbox" name="test" />
``:code
##### ``OPTGROUP``
Allows you to group multiple options in a SELECT and it is useful to customize the fields using CSS.
``OPTGROUP``:inxx
``
>>> print SELECT('a', OPTGROUP('b', 'c'))
<select>
<option value="a">a</option>
<optgroup>
<option value="b">b</option>
<option value="c">c</option>
</optgroup>
</select>
``:code
##### ``OPTION``
This should only be used as part of a SELECT/OPTION combination.
``OPTION``:inxx
``
>>> print OPTION('<hello>', XML('<b>world</b>'), _value='a')
<option value="a">&lt;hello&gt;<b>world</b></option>
``:code
As in the case of ``INPUT``, web2py make a distinction between "_value" (the value of the OPTION), and "value" (the current value of the enclosing select). If they are equal, the option is "selected".
``selected``:inxx
``
>>> print SELECT('a', 'b', value='b'):
<select>
<option value="a">a</option>
<option value="b" selected="selected">b</option>
</select>
``:code
##### ``P``
``P``:inxx
This is for tagging a paragraph.
``
>>> print P('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<p id="0" class="test">&lt;hello&gt;<b>world</b></p>
``:code
##### ``PRE``
``PRE``:inxx
Generates a ``<pre>...</pre>`` tag for displaying pre-formatted text. The ``CODE`` helper is generally preferable for code listings.
``
>>> print PRE('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<pre id="0" class="test">&lt;hello&gt;<b>world</b></pre>
``:code
##### ``SCRIPT``
``SCRIPT``:inxx
This is include or link a script, such as JavaScript. The content between the tags is rendered as an HTML comment, for the benefit of really old browsers.
``
>>> print SCRIPT('alert("hello world");', _type='text/javascript')
<script type="text/javascript"><!--
alert("hello world");
//--></script>
``:code
##### ``SELECT``
``SELECT``:inxx
Makes a ``<select>...</select>`` tag. This is used with the ``OPTION`` helper. Those ``SELECT`` arguments that are not ``OPTION`` objects are automatically converted to options.
``
>>> print SELECT('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<select id="0" class="test">
<option value="&lt;hello&gt;">&lt;hello&gt;</option>
<option value="&lt;b&gt;world&lt;/b&gt;"><b>world</b></option>
</select>
``:code
##### ``SPAN``
``SPAN``:inxx
Similar to ``DIV`` but used to tag inline (rather than block) content.
``
>>> print SPAN('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<span id="0" class="test">&lt;hello&gt;<b>world</b></span>
``:code
##### ``STYLE``
``STYLE``:inxx
Similar to script, but used to either include or link CSS code.
Here the CSS is included:
``
>>> print STYLE(XML('body {color: white}'))
<style><!--
body { color: white }
//--></style>
``:code
and here it is linked:
``
>>> print STYLE(_src='style.css')
<style src="style.css"><!--
//--></style>
``:code
##### ``TABLE``, ``TR``, ``TD``
``TABLE``:inxx ``TR``:inxx ``TD``:inxx
These tags (along with the optional ``THEAD``, ``TBODY`` and ``TFOOTER`` helpers) are used to build HTML tables.
``
>>> print TABLE(TR(TD('a'), TD('b')), TR(TD('c'), TD('d')))
<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>
``:code
``TR`` expects ``TD`` content; arguments that are not ``TD`` objects are converted automatically.
``
>>> print TABLE(TR('a', 'b'), TR('c', 'd'))
<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>
``:code
It is easy to convert a Python array into an HTML table using Python's ``*`` function arguments notation, which maps list elements to positional function arguments.
Here, we will do it line by line:
``
>>> table = [['a', 'b'], ['c', 'd']]
>>> print TABLE(TR(*table[0]), TR(*table[1]))
<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>
``:code
Here we do all lines at once:
``
>>> table = [['a', 'b'], ['c', 'd']]
>>> print TABLE(*[TR(*rows) for rows in table])
<table><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>
``:code
##### ``TBODY``
``TBODY``:inxx
This is used to tag rows contained in the table body, as opposed to header or footer rows. It is optional.
``
>>> print TBODY(TR('<hello>'), _class='test', _id=0)
<tbody id="0" class="test"><tr><td>&lt;hello&gt;</td></tr></tbody>
``:code
##### ``TEXTAREA``
``TEXTAREA``:inxx
This helper makes a ``<textarea>...</textarea>`` tag.
``
>>> print TEXTAREA('<hello>', XML('<b>world</b>'), _class='test')
<textarea class="test" cols="40" rows="10">&lt;hello&gt;<b>world</b></textarea>
``:code
The only caveat is that its optional "value" overrides its content (inner HTML)
``
>>> print TEXTAREA(value="<hello world>", _class="test")
<textarea class="test" cols="40" rows="10">&lt;hello world&gt;</textarea>
``:code
##### ``TFOOT``
``TFOOT``:inxx
This is used to tag table footer rows.
``
>>> print TFOOT(TR(TD('<hello>')), _class='test', _id=0)
<tfoot id="0" class="test"><tr><td>&lt;hello&gt;</td></tr></tfoot>
``:code
##### ``TH``
``TH``:inxx
This is used instead of ``TD`` in table headers.
``
>>> print TH('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<th id="0" class="test">&lt;hello&gt;<b>world</b></th>
``:code
##### ``THEAD``
``THEAD``:inxx
This is used to tag table header rows.
``
>>> print THEAD(TR(TH('<hello>')), _class='test', _id=0)
<thead id="0" class="test"><tr><th>&lt;hello&gt;</th></tr></thead>
``:code
##### ``TITLE``
``TITLE``:inxx
This is used to tag the title of a page in an HTML header.
``
>>> print TITLE('<hello>', XML('<b>world</b>'))
<title>&lt;hello&gt;<b>world</b></title>
``:code
##### ``TR``
``TR``:inxx
Tags a table row. It should be rendered inside a table and contain ``<td>...</td>`` tags. ``TR`` arguments that are not ``TD`` objects will be automatically converted.
``
>>> print TR('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<tr id="0" class="test"><td>&lt;hello&gt;</td><td><b>world</b></td></tr>
``:code
##### ``TT``
``TT``:inxx
Tags text as typewriter (monospaced) text.
``
>>> print TT('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<tt id="0" class="test">&lt;hello&gt;<b>world</b></tt>
``:code
##### ``UL``
Signifies an Unordered List and should contain LI items. If its content is not tagged as LI, UL does it automatically.
``UL``:inxx
``
>>> print UL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<ul id="0" class="test"><li>&lt;hello&gt;</li><li><b>world</b></li></ul>
``:code
##### ``embed64``
``embed64(filename=None, file=None, data=None, extension='image/gif')`` encodes the provided (binary) data into base64.
filename: if provided, opens and reads this file in 'rb' mode.
file: if provided, reads this file.
data: if provided, uses the provided data.
``embed64``:inxx
##### ``xmlescape``
``xmlescape(data, quote=True)`` returns an escaped string of the provided data.
``xmlescape``:inxx
``
>>> print xmlescape('<hello>')
&lt;hello&gt;
``:code
#### Custom helpers
##### ``TAG``
``TAG``:inxx
Sometimes you need to generate custom XML tags. web2py provides ``TAG``, a universal tag generator.
``
{{=TAG.name('a', 'b', _c='d')}}
``:code
generates the following XML
``
<name c="d">ab</name>
``:code
Arguments "a", "b", and "d" are automatically escaped; use the ``XML`` helper to suppress this behavior. Using ``TAG`` you can generate HTML/XML tags not already provided by the API. TAGs can be nested, and are serialized with ``str().``
An equivalent syntax is:
``
{{=TAG['name']('a', 'b', c='d')}}
``:code
If the TAG object is created with an empty name, it can be used to concatenate multiple strings and HTML helpers together without inserting them into a surrounding tag, but this use is deprecated. Use the ``CAT`` helper instead.
Notice that ``TAG`` is an object, and ``TAG.name`` or ``TAG['name']`` is a function that returns a temporary helper class.
##### ``MENU``
``MENU``:inxx

+In such cases you have a couple of options.
+You can use the ``data`` argument (this time without a leading underscore) to pass a dictionary of related attributes without their leading hyphen, and the output will have the desired combinations e.g.
+
+``
+>>> print DIV('text', data={'role': 'collapsible'})
+<div data-role="collapsible">text</div>
+``:code
+
+or you can instead pass the attributes as a dictionary and make use of Python's ``**`` function arguments notation, which maps a dictionary of (key:value) pairs into a set of keyword arguments:
``
>>> print DIV('text', **{'_data-role': 'collapsible'})
<div data-role="collapsible">text</div>
``:code
+Note that more elaborate entries will introduce HTML character entities, but they will work nonetheless e.g.
+
+``
+>>> print DIV('text', data={'options':'{"mode":"calbox", "useNewStyle":true}'})
+<div data-options="{&quot;mode&quot;:&quot;calbox&quot;, &quot;useNewStyle&quot;:true}">text</div>
+``:code
+
You can also dynamically create special TAGs:
-In such cases, you can instead pass the attributes as a dictionary and make use of Python's ``**`` function arguments notation, which map a dictionary of (key:value) pairs into a set of keyword arguments:
``
>>> print DIV('text', **{'_data-role': 'collapsible'})
<div data-role="collapsible">text</div>
``:code
You can also dynamically create special TAGs:

+##### ``IFRAME``
+
+This helper includes another web page in the current page. The url of the other page is specified via the "_src" attribute.
+
+``IFRAME``:inxx
+``
+>>> print IFRAME(_src='http://www.web2py.com')
+<iframe src="http://www.web2py.com"></iframe>
+``:code
+
+##### ``IMG``
+``IMG``:inxx
+
+It can be used to embed images into HTML:
+
+``
+>>> IMG(_src='http://example.com/image.png',_alt='test')
+<img src="http://example.com/image.ong" alt="rest" />
+``:code
+
+Here is a combination of A, IMG, and URL helpers for including a static image with a link:
+
+``
+>>> A(IMG(_src=URL('static','logo.png'), _alt="My Logo"),
+ _href=URL('default','index'))
+<a href="/myapp/default/index">
+ <img src="/myapp/static/logo.png" alt="My Logo" />
+</a>
+``:code
+
##### ``INPUT``
``INPUT``:inxx
Creates an ``<input.../>`` tag. An input tag may not contain other tags, and is closed by ``/>`` instead of ``>``. The input tag has an optional attribute ``_type`` that can be set to "text" (the default), "submit", "checkbox", or "radio".
``
>>> print INPUT(_name='test', _value='a')
<input value="a" name="test" />
``:code
It also takes an optional special argument called "value", distinct from "_value". The latter sets the default value for the input field; the former sets its current value. For an input of type "text", the former overrides the latter:
``
>>> print INPUT(_name='test', _value='a', value='b')
<input value="b" name="test" />
``:code
For radio buttons, ``INPUT`` selectively sets the "checked" attribute:
``radio``:inxx
``
>>> for v in ['a', 'b', 'c']:
>>> print INPUT(_type='radio', _name='test', _value=v, value='b'), v
<input value="a" type="radio" name="test" /> a
<input value="b" type="radio" checked="checked" name="test" /> b
<input value="c" type="radio" name="test" /> c
``:code
and similarly for checkboxes:
``checkbox``:inxx
``
>>> print INPUT(_type='checkbox', _name='test', _value='a', value=True)
<input value="a" type="checkbox" checked="checked" name="test" />
>>> print INPUT(_type='checkbox', _name='test', _value='a', value=False)
<input value="a" type="checkbox" name="test" />
``:code
##### ``LABEL``
##### ``INPUT``
``INPUT``:inxx
Creates an ``<input.../>`` tag. An input tag may not contain other tags, and is closed by ``/>`` instead of ``>``. The input tag has an optional attribute ``_type`` that can be set to "text" (the default), "submit", "checkbox", or "radio".
``
>>> print INPUT(_name='test', _value='a')
<input value="a" name="test" />
``:code
It also takes an optional special argument called "value", distinct from "_value". The latter sets the default value for the input field; the former sets its current value. For an input of type "text", the former overrides the latter:
``
>>> print INPUT(_name='test', _value='a', value='b')
<input value="b" name="test" />
``:code
For radio buttons, ``INPUT`` selectively sets the "checked" attribute:
``radio``:inxx
``
>>> for v in ['a', 'b', 'c']:
>>> print INPUT(_type='radio', _name='test', _value=v, value='b'), v
<input value="a" type="radio" name="test" /> a
<input value="b" type="radio" checked="checked" name="test" /> b
<input value="c" type="radio" name="test" /> c
``:code
and similarly for checkboxes:
``checkbox``:inxx
``
>>> print INPUT(_type='checkbox', _name='test', _value='a', value=True)
<input value="a" type="checkbox" checked="checked" name="test" />
>>> print INPUT(_type='checkbox', _name='test', _value='a', value=False)
<input value="a" type="checkbox" name="test" />
``:code
-##### ``IFRAME``
-
-This helper includes another web page in the current page. The url of the other page is specified via the "_src" attribute.
-
-``IFRAME``:inxx
-``
->>> print IFRAME(_src='http://www.web2py.com')
-<iframe src="http://www.web2py.com"></iframe>
-``:code
-
-##### ``IMG``
-``IMG``:inxx
-
-It can be used to embed images into HTML:
-
-``
->>> IMG(_src='http://example.com/image.png',_alt='test')
-<img src="http://example.com/image.ong" alt="rest" />
-``:code
-
-Here is a combination of A, IMG, and URL helpers for including a static image with a link:
-
-``
->>> A(IMG(_src=URL('static','logo.png'), _alt="My Logo"),
- _href=URL('default','index'))
-<a href="/myapp/default/index">
- <img src="/myapp/static/logo.png" alt="My Logo" />
-</a>
-``:code
-
##### ``LABEL``

- It is written in HTML5 and uses the "modernizr" ``modernizr``:cite library for backward compatibility. The actual layout include some extra conditional statements required by IE and they are omitted for brevity.
- It displays both ``response.title`` and ``response.subtitle`` which can be set in a model. If they are not set, it adopts the application name as title
- It includes the ``web2py_ajax.html`` file in the header which generated all the link and script import statements.
- It uses a modified version of Twitter Bootstrap for flexible layouts which works on mobile devices and re-arranges columns to fit small screens.
- It uses "analytics.js" to connect to Google Analytics.
+- The ``{{=auth.navbar(...)}}`` displays a welcome to the current user and links to the auth functions like login, logout, register, change password, etc. depending on context. It is a helper factory and its output can be manipulated as any other helper. It is placed in a ``{{try:}}...{{except:pass}}`` in case auth is undefined.
+- The ``{{=MENU(response.menu)}}`` displays the menu structure as ``<ul>...</ul>``.
- ``{{include}}`` is replaced by the content of the extending view when the page is rendered.
- By default it uses a conditional three column (the left and right sidebars can be turned off by the extending views)
- It uses the following classes: header, main, footer
- It contains the following blocks: statusbar, left_sidebar, center, right_sidebar, footer.
In viewsm, you can turn on and customize sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
``CSS``:inxx
Customizing the default layout without editing is easy because the welcome application is based on Twitter Bootstrap which is well documented and supports themes. In web2py four static files which are relevant to style:
- "css/web2py.css" contains web2py specific styles
- "css/bootstrap.min.css" contains the Twitter Bootstrap CSS style ``bootstrap``:cite ``Bootstrap``:inxx
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>
``:code
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.
### Blocks in views
``block``:inxx
The main way to make a view more modular is by using ``{{block...}}s`` and this mechanism is an alternative to the mechanism discussed in the previous section.
- It is written in HTML5 and uses the "modernizr" ``modernizr``:cite library for backward compatibility. The actual layout include some extra conditional statements required by IE and they are omitted for brevity.
- It displays both ``response.title`` and ``response.subtitle`` which can be set in a model. If they are not set, it adopts the application name as title
- It includes the ``web2py_ajax.html`` file in the header which generated all the link and script import statements.
- It uses a modified version of Twitter Bootstrap for flexible layouts which works on mobile devices and re-arranges columns to fit small screens.
- It uses "analytics.js" to connect to Google Analytics.
-- The ``{{=auth.navbar(...)}}`` displays a welcome to the current user and links to auth functions like login, logout, register, change password, etc. depending on context. It is a helper factory and its output can be manipulated as any other helper. It is placed in a ``{{try:}}...{{except:pass}}`` in case auth is undefined.
-- The ``{{=MENU(response.menu)`` displays the menu structure as ``<ul>...</ul>``.
- ``{{include}}`` is replaced by the content of the extending view when the page is rendered.
- By default it uses a conditional three column (the left and right sidebars can be turned off by the extending views)
- It uses the following classes: header, main, footer
- It contains the following blocks: statusbar, left_sidebar, center, right_sidebar, footer.
In views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
``CSS``:inxx
Customizing the default layout without editing is easy because the welcome application is based on Twitter Bootstrap which is well documented and supports themes. In web2py four static files which are relevant to style:
- "css/web2py.css" contains web2py specific styles
- "css/bootstrap.min.css" contains the Twitter Bootstrap CSS style ``bootstrap``:cite ``Bootstrap``:inxx
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>
``:code
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.
### Blocks in views
``block``:inxx
Another way to make a view more modular is by using ``{{block...}}s`` and this mechanism is an alternative to the mechanism discussed in the previous section.

Notice that helpers can be repeated using the multiplication operator:
``
>>> print BR()*5
<br /><br /><br /><br /><br />
``:code
##### ``CAT``
``CAT``:inxx
This helper concatenates other helpers, same as TAG[''].
``
>>> print CAT('Here is a ', A('link',_href=URL()), ', and here is some ', B('bold text'), '.')
Here is a <a href="/app/default/index">link</a>, and here is some <b>bold text</b>.
``:code
##### ``CENTER``
``CENTER``:inxx
This helper centers its content.
``
The "views/layout.html" that ships with the web2py scaffolding application **wel
<!-- The javascript =============================================
(Placed at the end of the document so the pages load faster) -->
<script src="{{=URL('static','js/bootstrap.min.js')}}"></script>
<script src="{{=URL('static','js/web2py_bootstrap.js')}}"></script>
{{if response.google_analytics_id:}}
<script src="{{=URL('static','js/analytics.js')}}"></script>
<script type="text/javascript">
analytics.initialize({
'Google Analytics':{trackingId:'{{=response.google_analytics_id}}'}
});</script>
{{pass}}
</body>
</html>
``:code
There are a few features of this default layout that make it very easy to use and customize:
- It is written in HTML5 and uses the "modernizr" ``modernizr``:cite library for backward compatibility. The actual layout include some extra conditional statements required by IE and they are omitted for brevity.
- It displays both ``response.title`` and ``response.subtitle`` which can be set in a model. If they are not set, it adopts the application name as title
- It includes the ``web2py_ajax.html`` file in the header which generated all the link and script import statements.
- It uses a modified version of Twitter Bootstrap for flexible layouts which works on mobile devices and re-arranges columns to fit small screens.
- It uses "analytics.js" to connect to Google Analytics.
- The ``{{=auth.navbar(...)}}`` displays a welcome to the current user and links to auth functions like login, logout, register, change password, etc. depending on context. It is a helper factory and its output can be manipulated as any other helper. It is placed in a ``{{try:}}...{{except:pass}}`` in case auth is undefined.
- The ``{{=MENU(response.menu)`` displays the menu structure as ``<ul>...</ul>``.
- ``{{include}}`` is replaced by the content of the extending view when the page is rendered.
- By default it uses a conditional three column (the left and right sidebars can be turned off by the extending views)
- It uses the following classes: header, main, footer
- It contains the following blocks: statusbar, left_sidebar, center, right_sidebar, footer.
In views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
``CSS``:inxx
Customizing the default layout without editing is easy because the welcome application is based on Twitter Bootstrap which is well documented and supports themes. In web2py four static files which are relevant to style:
- "css/web2py.css" contains web2py specific styles
- "css/bootstrap.min.css" contains the Twitter Bootstrap CSS style ``bootstrap``:cite ``Bootstrap``:inxx
- "css/web2py_bootstrap.css" contains with overrides some Bootstrap styles to conform to web2py needs.
- "js/bootstrap.min.js" which includes the libraries for menu effects, modals, panels.
Notice that halpers can be repeated using the multiplication operator:
``
>>> print BR()*5
<br /><br /><br /><br /><br />
``:code
##### ``CAT``
``CAT``:inxx
This helper concatenates other helpers, same as TAG[''].
``
>>> print CAT('Here is a ', A('link',_href=URL()), ', and here is some ', B('bold text'), '.')
Here is a <a href="/app/default/index">link</a>, and here is some <b>bold text</b>.
``:code
##### ``CENTER``
``CENTER``:inxx
This helper centers its content.
``
The "views/layout.html" that ships with the web2py scaffolding application **wel
<!-- The javascript =============================================
(Placed at the end of the document so the pages load faster) -->
<script src="{{=URL('static','js/bootstrap.min.js')}}"></script>
<script src="{{=URL('static','js/web2py_bootstrap.js')}}"></script>
{{if response.google_analytics_id:}}
<script src="{{=URL('static','js/analytics.js')}}"></script>
<script type="text/javascript">
analytics.initialize({
'Google Analytics':{trackingId:'{{=response.google_analytics_id}}'}
});</script>
{{pass}}
</body>
</html>
``:code
There are a few features of this default layout that make it very easy to use and customize:
- It is written in HTML5 and uses the "modernizr" ``modernizr``:cite library for backward compatibility. The actual layout include some extra conditional statements required by IE and they are omitted for brevity.
- It displays both ``response.title`` and ``response.subtitle`` which can be set in a model. If they are not set, it adopts the application name as title
- It includes the ``web2py_ajax.html`` file in the header which generated all the link and script import statements.
- It uses a modified version of Twitter Boostrap for flexible layouts which works on mobile devices and re-arranges columns to fit small screens.
- It uses "analytics.js" to connect to Google Analytics.
- The ``{{=auth.navbar(...)}}`` displays a welcome to the current user and links to auth functions like login, logout, register, change password, etc. depending on context. It is a helper factory and its output can be manipulated as any other helper. It is placed in a ``{{try:}}...{{except:pass}}`` in case auth is undefined.
- The ``{{=MENU(response.menu)`` displays the menu structure as ``<ul>...</ul>``.
- ``{{include}}`` is replaced by the content of the extending view when the page is rendered.
- By default it uses a conditional three column (the left and right sidebars can be turned off by the extending views)
- It uses the following classes: header, main, footer
- It contains the following blocks: statusbar, left_sidebar, center, right_sidebar, footer.
In views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
``CSS``:inxx
Customizing the default layout without editing is easy because the welcome application is based on Twitter Bootstrap which is well documented and supports themes. In web2py four static files which are relevant to style:
- "css/web2py.css" contains web2py specific styles
- "css/bootstrap.min.css" contains the Twitter Boostrap CSS style ``bootstrap``:cite ``Bootstrap``:inxx
- "css/web2py_bootstrap.css" contains with overrides some Bootstrap styles to conform to web2py needs.
- "js/bootstrap.min.js" which includes the libraries for menu effects, modals, panels.

``parent``:inxx ``sibling``:inxx
#### ``parent`` and ``siblings``
``parent`` returns the parent of the current element.
``
>>> a = DIV(SPAN('a'),DIV('b'))
>>> s = a.element('span')
>>> d = s.parent
>>> d['_class']='abc'
>>> print a
<div class="abc"><span>a</span><div>b</div></div>
>>> for e in s.siblings(): print e
<div>b</div>
``:code
#### Replacing elements
Elements that are matched can also be replaced or removed by specifying
the ``replace`` argument. Notice that a
list of the original matching elements is still returned as usual.
The "views/layout.html" that ships with the web2py scaffolding application **wel
{{include 'web2py_ajax.html'}}
{{
# using sidebars need to know what sidebar you want to use
left_sidebar_enabled = globals().get('left_sidebar_enabled',False)
right_sidebar_enabled = globals().get('right_sidebar_enabled',False)
middle_columns = {0:'span12',1:'span9',2:'span6'}[
(left_sidebar_enabled and 1 or 0)+(right_sidebar_enabled and 1 or 0)]
}}
{{block head}}{{end}}
</head>
<body>
<!-- Navbar ================================================== -->
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="flash">{{=response.flash or ''}}</div>
<div class="navbar-inner">
<div class="container">
{{=response.logo or ''}}
<ul id="navbar" class="nav pull-right">
{{='auth' in globals() and auth.navbar(mode="dropdown") or ''}}
</ul>
<div class="nav-collapse">
{{if response.menu:}}
{{=MENU(response.menu)}}
{{pass}}
</div><!--/.nav-collapse -->
</div>
</div>
</div><!--/top navbar -->
<div class="container">
<!-- Masthead ================================================== -->
<header class="mastheader row" id="header">
<div class="span12">
<div class="page-header">
<h1>
{{=response.title or request.application}}
<small>{{=response.subtitle or ''}}</small>
The "views/layout.html" that ships with the web2py scaffolding application **wel
{{block center}}
{{include}}
{{end}}
</div>
{{if right_sidebar_enabled:}}
<div class="span3">
{{block right_sidebar}}
<h3>Right Sidebar</h3>
<p></p>
{{end}}
</div>
{{pass}}
</section><!--/main-->
<!-- Footer ================================================== -->
<div class="row">
<footer class="footer span12" id="footer">
<div class="footer-content">
{{block footer}} <!-- this is default footer -->
...
{{end}}
</div>
</footer>
</div>
</div> <!-- /container -->
<!-- The javascript =============================================
(Placed at the end of the document so the pages load faster) -->
<script src="{{=URL('static','js/bootstrap.min.js')}}"></script>
<script src="{{=URL('static','js/web2py_bootstrap.js')}}"></script>
{{if response.google_analytics_id:}}
<script src="{{=URL('static','js/analytics.js')}}"></script>
<script type="text/javascript">
analytics.initialize({
'Google Analytics':{trackingId:'{{=response.google_analytics_id}}'}
});</script>
{{pass}}
</body>
</html>
Inside a block, you can use the expression ``{{super}}`` to include the content
Hello World!!!
{{block mysidebar}}
{{super}}
my new sidebar!!!
{{end}}
``:code
we get:
``
<html>
<body>
Hello World!!!
<div class="sidebar">
my default sidebar
my new sidebar!!!
</div>
</body>
</html>
``:code
``parent``:inxx ``sibling``Linxx
#### ``parent`` and ``siblings``
``parent`` returns the parent of the current element.
``
>>> a = DIV(SPAN('a'),DIV('b'))
>>> s = a.element('span')
>>> d = s.parent
>>> d['_class']='abc'
>>> print a
<div class="abc"><span>a</span><div>b</div></div>
>>> for e in s.siblings(): print e
<div>b</div>
``:code
#### Replacing elements
Elements that are matched can also be replaced or removed by specifying
the ``replace`` argument. Notice that a
list of the original matching elements is still returned as usual.
The "views/layout.html" that ships with the web2py scaffolding application **wel
{{include 'web2py_ajax.html'}}
{{
# using sidebars need to know what sidebar you want to use
left_sidebar_enabled = globals().get('left_sidebar_enabled',False)
right_sidebar_enabled = globals().get('right_sidebar_enabled',False)
middle_columns = {0:'span12',1:'span9',2:'span6'}[
(left_sidebar_enabled and 1 or 0)+(right_sidebar_enabled and 1 or 0)]
}}
{{block head}}{{end}}
</head>
<body>
<!-- Navbar ================================================== -->
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="flash">{{=response.flash or ''}}</div>
<div class="navbar-inner">
<div class="container">
{{=response.logo or ''}}
<ul id="navbar" class="nav pull-right">
{{='auth' in globals() and auth.navbar(mode="dropdown") or ''}}
</ul>
<div class="nav-collapse">
{{if response.menu:}}
{{=MENU(response.menu)}}
{{pass}}
</div><!--/.nav-collapse -->
</div>
</div>
</div><!--/top navbar -->
<div class="container">
<!-- Masthead ================================================== -->
<header class="mastheader row" id="header">
<div class="span12">
<div class="page-header">
<h1>
{{=response.title or request.application}}
<small>{{=response.subtitle or ''}}</small>
The "views/layout.html" that ships with the web2py scaffolding application **wel
{{block center}}
{{include}}
{{end}}
</div>
{{if right_sidebar_enabled:}}
<div class="span3">
{{block right_sidebar}}
<h3>Right Sidebar</h3>
<p></p>
{{end}}
</div>
{{pass}}
</section><!--/main-->
<!-- Footer ================================================== -->
<div class="row">
<footer class="footer span12" id="footer">
<div class="footer-content">
{{block footer}} <!-- this is default footer -->
...
{{end}}
</div>
</footer>
</div>
</div> <!-- /container -->
<!-- The javascript =============================================
(Placed at the end of the document so the pages load faster) -->
<script src="{{=URL('static','js/bootstrap.min.js')}}"></script>
<script src="{{=URL('static','js/web2py_bootstrap.js')}}"></script>
{{if response.google_analytics_id:}}
<script src="{{=URL('static','js/analytics.js')}}"></script>
<script type="text/javascript">
analytics.initialize({
'Google Analytics':{trackingId:'{{=response.google_analytics_id}}'}
});</script>
{{pass}}
</body>
</html>
Inside a block, you can use the expression ``{{super}}`` to include the content
Hello World!!!
{{block mysidebar}}
{{super}}
my new sidebar!!!
{{end}}
``:code
we get:
``
<html>
<body>
Hello World!!!
<div class="sidebar">
my default sidebar
my new sidebar!!!
</div>
</body>
</html>
``:code
-

##### ``CAT``
``CAT``:inxx
This helper concatenates other helpers, same as TAG[''].
``
>>> print CAT('Here is a ', A('link',_href=URL()), ', and here is some ', B('bold text'), '.')
Here is a <a href="/app/default/index">link</a>, and here is some <b>bold text</b>.
``:code
##### ``CENTER``
``CENTER``:inxx
This helper centers its content.
``
>>> print CENTER('<hello>', XML('<b>world</b>'),
>>> _class='test', _id=0)
<center id="0" class="test">&lt;hello&gt;<b>world</b></center>
``:code
##### ``CODE``
``CODE``:inxx
To be used for building ``META`` tags in the ``HTML`` head. For example:
>>> print META(_name='security', _content='high')
<meta name="security" content="high" />
``:code
##### ``MARKMIN``
Implements the markmin wiki syntax. It converts the input text into output html according to the markmin rules described in the example below:
``MARKMIN``:inxx
``
>>> print MARKMIN("this is **bold** or ''italic'' and this [[a link http://web2py.com]]")
<p>this is <b>bold</b> or <i>italic</i> and
this <a href="http://web2py.com">a link</a></p>
``:code
The markmin syntax is described in this file that ships with web2py:
``
http://127.0.0.1:8000/examples/static/markmin.html
``:code
You can use markmin to generate HTML, LaTeX and PDF documents:
##### ``CAT`` (1.98.1 and up)
``CAT``:inxx
This helper concatenates other helpers, same as TAG[''].
``
>>> print CAT('Here is a ', A('link',_href=URL()), ', and here is some ', B('bold text'), '.')
Here is a <a href="/app/default/index">link</a>, and here is some <b>bold text</b>.
``:code
##### ``CENTER``
``CENTER``:inxx
This helper centers its content.
``
>>> print CENTER('<hello>', XML('<b>world</b>'),
>>> _class='test', _id=0)
<center id="0" class="test">&lt;hello&gt;<b>world</b></center>
``:code
##### ``CODE``
``CODE``:inxx
To be used for building ``META`` tags in the ``HTML`` head. For example:
>>> print META(_name='security', _content='high')
<meta name="security" content="high" />
``:code
##### ``MARKMIN``
Implements the markmin wiki syntax. It converts the input text into output html according to the markmin rules described in the example below:
``MARKMIN``:inxx
``
>>> print MARKMIN("this is **bold** or ''italic'' and this [[a link http://web2py.com]]")
<p>this is <b>bold</b> or <i>italic</i> and
this <a href="http://web2py.com">a link</a></p>
``:code
The markmin syntax is described in this file that ships with web2py:
``
http://127.0.0.1:8000/examples/static/markmin.html
``:code
-and some examples are shown in chapter 12 in the context of plugin_wiki, which uses MARKMIN extensively.
-
You can use markmin to generate HTML, LaTeX and PDF documents:

The "views/layout.html" that ships with the web2py scaffolding application **welcome** (stripped down of some optional parts) is quite complex but it has the following structure:
The "views/layout.html" that ships with the web2py scaffolding application **welcome** (stripped down of some optional parts) is quote complex but is has the following structure:

can be used to build complex expressions that can then be serialized to XML``xml-w``:cite ``xml-o``:cite. For example:
``
{{=DIV(B(I("hello ", "<world>"))), _class="myclass")}}
``:code
is rendered:
``
<div class="myclass"><b><i>hello &lt;world&gt;</i></b></div>
``:code
Helpers can also be serialized into strings, equivalently, with the ``__str__`` and the ``xml`` methods:
``
>>> print str(DIV("hello world"))
<div>hello world</div>
>>> print DIV("hello world").xml()
<div>hello world</div>
``
``Document Object Model (DOM)``:inxx
The helpers mechanism in web2py is more than a system to generate HTML without concatenating strings. It provides a server-side representation of the Document Object Model (DOM).
The constructor of a ``FORM``, and of ``SQLFORM``, can also take a special argum
These helpers are for paragraph headings and subheadings:
``
>>> print H1('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<h1 id="0" class="test">&lt;hello&gt;<b>world</b></h1>
``:code
##### ``HEAD``
For tagging the HEAD of an HTML page.
``HEAD``:inxx
``
>>> print HEAD(TITLE('<hello>', XML('<b>world</b>')))
<head><title>&lt;hello&gt;<b>world</b></title></head>
``:code
##### ``HTML``
``HTML``:inxx ``XHTML``:inxx
This helper is a little different. In addition to making the ``<html>`` tags,
it prepends the tag with a doctype string``xhtml-w,xhtml-o,xhtml-school``:cite .
``
>>> print HTML(BODY('<hello>', XML('<b>world</b>')))
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><body>&lt;hello&gt;<b>world</b></body></html>
``:code
can be used to build complex expressions that can then be serialized to XML``xml:w``:cite ``xml:o``:cite. For example:
``
{{=DIV(B(I("hello ", "<world>"))), _class="myclass")}}
``:code
is rendered:
``
<div class="myclass"><b><i>hello &lt;world&gt;</i></b></div>
``:code
Helpers can also be serialized into strings, equivalently, with the ``__str__`` and the ``xml`` methods:
``
>>> print str(DIV("hello world"))
<div>hello world</div>
>>> print DIV("hello world").xml()
<div>hello world</div>
``
``Document Object Model (DOM)``:inxx
The helpers mechanism in web2py is more than a system to generate HTML without concatenating strings. It provides a server-side representation of the Document Object Model (DOM).
The constructor of a ``FORM``, and of ``SQLFORM``, can also take a special argum
These helpers are for paragraph headings and subheadings:
``
>>> print H1('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<h1 id="0" class="test">&lt;hello&gt;<b>world</b></h1>
``:code
##### ``HEAD``
For tagging the HEAD of an HTML page.
``HEAD``:inxx
``
>>> print HEAD(TITLE('<hello>', XML('<b>world</b>')))
<head><title>&lt;hello&gt;<b>world</b></title></head>
``:code
##### ``HTML``
``HTML``:inxx ``XHTML``:inxx
This helper is a little different. In addition to making the ``<html>`` tags,
it prepends the tag with a doctype string``xhtml:w,xhtml:o,xhtml:school``:cite .
``
>>> print HTML(BODY('<hello>', XML('<b>world</b>')))
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><body>&lt;hello&gt;<b>world</b></body></html>
``:code

#### Default page layout
+``Twitter Bootstrap``:inxx
+
+The "views/layout.html" that ships with the web2py scaffolding application **welcome** (stripped down of some optional parts) is quote complex but is has the following structure:
``
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>{{=response.title or request.application}}</title>
...
<script src="{{=URL('static','js/modernizr.custom.js')}}"></script>
{{
response.files.append(URL('static','css/web2py.css'))
+ response.files.append(URL('static','css/bootstrap.min.css'))
+ response.files.append(URL('static','css/bootstrap-responsive.min.css'))
+ response.files.append(URL('static','css/web2py_bootstrap.css'))
}}
{{include 'web2py_ajax.html'}}
{{
# using sidebars need to know what sidebar you want to use
left_sidebar_enabled = globals().get('left_sidebar_enabled',False)
right_sidebar_enabled = globals().get('right_sidebar_enabled',False)
+ middle_columns = {0:'span12',1:'span9',2:'span6'}[
+ (left_sidebar_enabled and 1 or 0)+(right_sidebar_enabled and 1 or 0)]
}}
+ {{block head}}{{end}}
</head>
+<body>
+ <!-- Navbar ================================================== -->
+ <div class="navbar navbar-inverse navbar-fixed-top">
<div class="flash">{{=response.flash or ''}}</div>
<div class="navbar-inner">
<div class="container">
+ {{=response.logo or ''}}
+ <ul id="navbar" class="nav pull-right">
+ {{='auth' in globals() and auth.navbar(mode="dropdown") or ''}}
+ </ul>
+ <div class="nav-collapse">
+ {{if response.menu:}}
+ {{=MENU(response.menu)}}
+ {{pass}}
+ </div><!--/.nav-collapse -->
</div>
</div>
+ </div><!--/top navbar -->
+
+ <div class="container">
+ <!-- Masthead ================================================== -->
+ <header class="mastheader row" id="header">
+ <div class="span12">
+ <div class="page-header">
+ <h1>
+ {{=response.title or request.application}}
+ <small>{{=response.subtitle or ''}}</small>
+ </h1>
+ </div>
+ </div>
+ </header>
<section id="main" class="main row">
{{if left_sidebar_enabled:}}
+ <div class="span3 left-sidebar">
+ {{block left_sidebar}}
+ <h3>Left Sidebar</h3>
+ <p></p>
+ {{end}}
</div>
{{pass}}
+ <div class="{{=middle_columns}}">
+ {{block center}}
+ {{include}}
+ {{end}}
</div>
{{if right_sidebar_enabled:}}
+ <div class="span3">
+ {{block right_sidebar}}
+ <h3>Right Sidebar</h3>
+ <p></p>
+ {{end}}
</div>
{{pass}}
+ </section><!--/main-->
+
+ <!-- Footer ================================================== -->
+ <div class="row">
+ <footer class="footer span12" id="footer">
+ <div class="footer-content">
+ {{block footer}} <!-- this is default footer -->
+ ...
+ {{end}}
+ </div>
+ </footer>
+ </div>
+ </div> <!-- /container -->
+
+ <!-- The javascript =============================================
+ (Placed at the end of the document so the pages load faster) -->
+ <script src="{{=URL('static','js/bootstrap.min.js')}}"></script>
+ <script src="{{=URL('static','js/web2py_bootstrap.js')}}"></script>
+ {{if response.google_analytics_id:}}
+ <script src="{{=URL('static','js/analytics.js')}}"></script>
+ <script type="text/javascript">
+ analytics.initialize({
+ 'Google Analytics':{trackingId:'{{=response.google_analytics_id}}'}
+ });</script>
+ {{pass}}
</body>
</html>
``:code
There are a few features of this default layout that make it very easy to use and customize:
- It is written in HTML5 and uses the "modernizr" ``modernizr``:cite library for backward compatibility. The actual layout include some extra conditional statements required by IE and they are omitted for brevity.
- It displays both ``response.title`` and ``response.subtitle`` which can be set in a model. If they are not set, it adopts the application name as title
- It includes the ``web2py_ajax.html`` file in the header which generated all the link and script import statements.
+- It uses a modified version of Twitter Boostrap for flexible layouts which works on mobile devices and re-arranges columns to fit small screens.
+- It uses "analytics.js" to connect to Google Analytics.
- The ``{{=auth.navbar(...)}}`` displays a welcome to the current user and links to auth functions like login, logout, register, change password, etc. depending on context. It is a helper factory and its output can be manipulated as any other helper. It is placed in a ``{{try:}}...{{except:pass}}`` in case auth is undefined.
- The ``{{=MENU(response.menu)`` displays the menu structure as ``<ul>...</ul>``.
- ``{{include}}`` is replaced by the content of the extending view when the page is rendered.
- By default it uses a conditional three column (the left and right sidebars can be turned off by the extending views)
- It uses the following classes: header, main, footer
- It contains the following blocks: statusbar, left_sidebar, center, right_sidebar, footer.
In views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
``CSS``:inxx
Customizing the default layout without editing is easy because the welcome application is based on Twitter Bootstrap which is well documented and supports themes. In web2py four static files which are relevant to style:
+- "css/web2py.css" contains web2py specific styles
+- "css/bootstrap.min.css" contains the Twitter Boostrap CSS style ``bootstrap``:cite ``Bootstrap``:inxx
+- "css/web2py_bootstrap.css" contains with overrides some Bootstrap styles to conform to web2py needs.
+- "js/bootstrap.min.js" which includes the libraries for menu effects, modals, panels.
#### Default page layout
-``superfish``:inxx ``ez.css``:inxx
-Below is the "views/layout.html" that ships with the web2py scaffolding application **welcome** (stripped down of some optional parts). Any new application will have a similar default layout:
``
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>{{=response.title or request.application}}</title>
-
- <!-- http://dev.w3.org/html5/markup/meta.name.html -->
- <meta name="application-name" content="{{=request.application}}" />
<script src="{{=URL('static','js/modernizr.custom.js')}}"></script>
- <!-- include stylesheets -->
{{
- response.files.append(URL('static','css/skeleton.css'))
response.files.append(URL('static','css/web2py.css'))
- response.files.append(URL('static','css/superfish.css'))
- response.files.append(URL('static','js/superfish.js'))
}}
{{include 'web2py_ajax.html'}}
- <script type="text/javascript">
- jQuery(function(){ jQuery('ul.sf-menu').supersubs({minWidth:12,maxWidth:30,extraWidth:3}).superfish(); });
- </script>
-
{{
# using sidebars need to know what sidebar you want to use
left_sidebar_enabled = globals().get('left_sidebar_enabled',False)
right_sidebar_enabled = globals().get('right_sidebar_enabled',False)
- middle_columns = {0:'sixteen',1:'twelve',2:'eight'}[
- (left_sidebar_enabled and 1 or 0)+(right_sidebar_enabled and 1 or 0)]
}}
</head>
-<body>
- <div class="wrapper"><!-- for sticky footer -->
-
- <div class="topbar">
- <div class="container">
- <div class="sixteen columns">
- <div id="navbar">
- {{='auth' in globals() and auth.navbar(separators=(' ',' | ',''))}}
- </div>
- <div id="menu">
- {{=MENU(response.menu,
- _class='mobile-menu' if is_mobile else 'sf-menu',
- mobile=request.user_agent().is_mobile)}}
- </div>
- </div>
- </div>
- </div><!-- topbar -->
<div class="flash">{{=response.flash or ''}}</div>
-
<div class="header">
<div class="container">
- <div class="sixteen columns">
- <h1 class="remove-bottom" style="margin-top: .5em;">
- {{=response.title or request.application}}
- </h1>
- <h5>{{=response.subtitle or ''}}</h5>
- </div>
-
- <div class="sixteen columns">
- <div class="statusbar">
- {{block statusbar}}
- <span class="breadcrumbs">{{=request.function}}</span>
- {{end}}
- </div>
- </div>
</div>
</div>
- <div class="main">
<div class="container">
{{if left_sidebar_enabled:}}
- <div class="four columns left-sidebar">
- {{block left_sidebar}}
- <h3>Left Sidebar</h3>
- <p></p>
- {{end}}
</div>
{{pass}}
- <div class="{{=middle_columns}} columns center">
- {{block center}}
- {{include}}
- {{end}}
</div>
{{if right_sidebar_enabled:}}
- <div class="four columns">
- {{block right_sidebar}}
- <h3>Right Sidebar</h3>
- <p></p>
- {{end}}
</div>
{{pass}}
- </div><!-- container -->
- </div><!-- main -->
-
- <div class="push"></div>
- </div><!-- wrapper -->
-
- <div class="footer">
- <div class="container header">
- <div class="sixteen columns">
- {{block footer}} <!-- this is default footer -->
- <div class="footer-content" >
- {{=T('Copyright')}} &#169; 2011
- <div style="float: right;">
- <a href="http://www.web2py.com/">
- <img style="padding-bottom: 0;"
- src="{{=URL('static','images/poweredby.png')}}"/>
- </a>
- </div>
- </div>
- {{end}}
- </div>
- </div><!-- container -->
- </div><!-- footer -->
-
</body>
</html>
-
``:code
There are a few features of this default layout that make it very easy to use and customize:
- It is written in HTML5 and uses the "modernizr" ``modernizr``:cite library for backward compatibility. The actual layout include some extra conditional statements required by IE and they are omitted for brevity.
- It displays both ``response.title`` and ``response.subtitle`` which can be set in a model. If they are not set, it adopts the application name as title
- It includes the ``web2py_ajax.html`` file in the header which generated all the link and script import statements.
-- It uses a modified version of "skeleton" ``skeleton``:cite a library for flexible layouts which works on mobile devices and re-arranges columns to fit small screens.
-- It uses "superfish.js" ``superfish``:cite for dynamic cascading menus. There is an explicit script to activate the superfish cascading menu and it can be removed if not necessary.
- The ``{{=auth.navbar(...)}}`` displays a welcome to the current user and links to auth functions like login, logout, register, change password, etc. depending on context. It is a helper factory and its output can be manipulated as any other helper. It is placed in a ``{{try:}}...{{except:pass}}`` in case auth is undefined.
- The ``{{=MENU(response.menu)`` displays the menu structure as ``<ul>...</ul>``.
- ``{{include}}`` is replaced by the content of the extending view when the page is rendered.
- By default it uses a conditional three column (the left and right sidebars can be turned off by the extending views)
- It uses the following classes: header, main, footer
- It contains the following blocks: statusbar, left_sidebar, center, right_sidebar, footer.
Views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
``CSS``:inxx
Customizing the default layout without editing is very easy because the CSS files are documented:
-- "bootstrap.min.css" contains the Twitter Boostrap CSS style ``bootstrap``:cite ``Bootstrap``:inxx
-- "web2py.css" contains web2py specific styles

+Notice that halpers can be repeated using the multiplication operator:
+
+``
+>>> print BR()*5
+<br /><br /><br /><br /><br />
+``:code
+
##### ``CAT`` (1.98.1 and up)
``CAT``:inxx
This helper concatenates other helpers, same as TAG[''].
``
>>> print CAT('Here is a ', A('link',_href=URL()), ', and here is some ', B('bold text'), '.')
Here is a <a href="/app/default/index">link</a>, and here is some <b>bold text</b>.
``:code
##### ``CENTER``
``CENTER``:inxx
This helper centers its content.
``
>>> print CENTER('<hello>', XML('<b>world</b>'),
>>> _class='test', _id=0)
<center id="0" class="test">&lt;hello&gt;<b>world</b></center>
``:code
##### ``CODE``
The third item in each list/tuple can be an HTML helper (which could include nes
Each menu item can have a fourth argument that is a nested submenu (and so on recursively):
``
>>> print MENU([['One', False, 'link1', [['Two', False, 'link2']]]])
<ul class="web2py-menu web2py-menu-vertical">
<li class="web2py-menu-expand">
<a href="link1">One</a>
<ul class="web2py-menu-vertical">
<li><a href="link2">Two</a></li>
</ul>
</li>
</ul>
``:code
A menu item can also have an optional 5th element, which is a boolean. When false, the menu item is ignored by the MENU helper.
The MENU helper takes the following optional arguments:
- ``_class``: defaults to "web2py-menu web2py-menu-vertical" and sets the class of the outer UL elements.
- ``ul_class``: defaults to "web2py-menu-vertical" and sets the class of the inner UL elements.
- ``li_class``: defaults to "web2py-menu-expand" and sets the class of the inner LI elements.
+- ``li_first``: allows to add a class to the first list element.
+- ``li_last``: allows to add a class to the last list element.
``mobile``:inxx
``MENU`` takes an optional argument ``mobile``. When set to ``True`` instead of building a recursive ``UL`` menu structure it returns a ``SELECT`` dropdown with all the menu options and a ``onchange`` attribute that redirects to the page corresponding to the selected option. This is designed an an alternative menu representation that increases usability on small mobile devices such as phones.
Normally the menu is used in a layout with the following syntax:
``
{{=MENU(response.menu, mobile=request.user_agent().is_mobile)}}
``
In this way a mobile device is automatically detected and the menu is rendered accordingly.
### ``BEAUTIFY``
``BEAUTIFY`` is used to build HTML representations of compound objects, including lists, tuples and dictionaries:
``
{{=BEAUTIFY({"a": ["hello", XML("world")], "b": (1, 2)})}}
``:code
``BEAUTIFY`` returns an XML-like object serializable to XML, with a nice looking representation of its constructor argument. In this case, the XML representation of:
``
Here's an example of listing all elements in an html string:
``
html = TAG('<a>xxx</a><b>yyy</b>')
for item in html.components: print item
``:code
``parent``:inxx ``sibling``Linxx
#### ``parent`` and ``siblings``
``parent`` returns the parent of the current element.
``
>>> a = DIV(SPAN('a'),DIV('b'))
>>> s = a.element('span')
>>> d = s.parent
>>> d['_class']='abc'
>>> print a
<div class="abc"><span>a</span><div>b</div></div>
>>> for e in s.siblings(): print e
<div>b</div>
``:code
+#### Replacing elements
+
+Elements that are matched can also be replaced or removed by specifying
+the ``replace`` argument. Notice that a
+list of the original matching elements is still returned as usual.
+
+``
+>>> a = DIV(SPAN('x'), DIV(SPAN('y'))
+>>> b = a.elements('span', replace=P('z')
+>>> print a
+<div><p>z</p><div><p>z</p></div>
+``:code
+
+``replace`` can be a callable. In this case it will be passed
+the original element and it is expected to return the replacement element:
+
+``
+>>> a = DIV(SPAN('x'), DIV(SPAN('y'))
+>>> b = a.elements('span', replace=lambda t: P(t[0])
+>>> print a
+<div><p>x</p><div><p>y</p></div>
+``:code
+
+If ``replace=None``, matching elements will be removed completely.
+
+``
+>>> a = DIV(SPAN('x'), DIV(SPAN('y'))
+>>> b = a.elements('span', replace=None)
+>>> print a
+<div></div>
+``:code
+
#### ``flatten`` ``flatten``:inxx
##### ``CAT`` (1.98.1 and up)
``CAT``:inxx
This helper concatenates other helpers, same as TAG[''].
``
>>> print CAT('Here is a ', A('link',_href=URL()), ', and here is some ', B('bold text'), '.')
Here is a <a href="/app/default/index">link</a>, and here is some <b>bold text</b>.
``:code
##### ``CENTER``
``CENTER``:inxx
This helper centers its content.
``
>>> print CENTER('<hello>', XML('<b>world</b>'),
>>> _class='test', _id=0)
<center id="0" class="test">&lt;hello&gt;<b>world</b></center>
``:code
##### ``CODE``
The third item in each list/tuple can be an HTML helper (which could include nes
Each menu item can have a fourth argument that is a nested submenu (and so on recursively):
``
>>> print MENU([['One', False, 'link1', [['Two', False, 'link2']]]])
<ul class="web2py-menu web2py-menu-vertical">
<li class="web2py-menu-expand">
<a href="link1">One</a>
<ul class="web2py-menu-vertical">
<li><a href="link2">Two</a></li>
</ul>
</li>
</ul>
``:code
A menu item can also have an optional 5th element, which is a boolean. When false, the menu item is ignored by the MENU helper.
The MENU helper takes the following optional arguments:
- ``_class``: defaults to "web2py-menu web2py-menu-vertical" and sets the class of the outer UL elements.
- ``ul_class``: defaults to "web2py-menu-vertical" and sets the class of the inner UL elements.
- ``li_class``: defaults to "web2py-menu-expand" and sets the class of the inner LI elements.
``mobile``:inxx
``MENU`` takes an optional argument ``mobile``. When set to ``True`` instead of building a recursive ``UL`` menu structure it returns a ``SELECT`` dropdown with all the menu options and a ``onchange`` attribute that redirects to the page corresponding to the selected option. This is designed an an alternative menu representation that increases usability on small mobile devices such as phones.
Normally the menu is used in a layout with the following syntax:
``
{{=MENU(response.menu, mobile=request.user_agent().is_mobile)}}
``
In this way a mobile device is automatically detected and the menu is rendered accordingly.
### ``BEAUTIFY``
``BEAUTIFY`` is used to build HTML representations of compound objects, including lists, tuples and dictionaries:
``
{{=BEAUTIFY({"a": ["hello", XML("world")], "b": (1, 2)})}}
``:code
``BEAUTIFY`` returns an XML-like object serializable to XML, with a nice looking representation of its constructor argument. In this case, the XML representation of:
``
Here's an example of listing all elements in an html string:
``
html = TAG('<a>xxx</a><b>yyy</b>')
for item in html.components: print item
``:code
``parent``:inxx ``sibling``Linxx
#### ``parent`` and ``siblings``
``parent`` returns the parent of the current element.
``
>>> a = DIV(SPAN('a'),DIV('b'))
>>> s = a.element('span')
>>> d = s.parent
>>> d['_class']='abc'
>>> print a
<div class="abc"><span>a</span><div>b</div></div>
>>> for e in s.siblings(): print e
<div>b</div>
``:code
#### ``flatten`` ``flatten``:inxx

+web2py uses ``{{ ... }}`` to escape Python code embedded in HTML. The advantage of using curly brackets instead of angle brackets is that it's transparent to all common HTML editors. This allows the developer to use those editors to create web2py views. These delimiters can be changed for example with
+
+``
+response.delimiters = ('<?','?>')
+``:code
+
+If this line is in a model it will be applied everywhere, if in a controller only to views for the controller actions, if inside an action only to the view for that action.
Since the developer is embedding Python code into HTML, the document should be indented according to HTML rules, and not Python rules. Therefore, we allow unindented Python inside the ``{{ ... }}`` tags. Since Python normally uses indentation to delimit blocks of code, we need a different way to delimit them; this is why the web2py template language makes use of the Python keyword ``pass``.
-------
A code block starts with a line ending with a colon and ends with a line beginning with ``pass``. The keyword ``pass`` is not necessary when the end of the block is obvious from the context.
-------
Here is an example:
``
{{
if i == 0:
response.write('i is 0')
else:
response.write('i is not 0')
pass
}}
``:code
Note that ``pass`` is a Python keyword, not a web2py keyword. Some Python editors, such as Emacs, use the keyword ``pass`` to signify the division of blocks and use it to re-indent code automatically.
An equivalent syntax is:
``
{{=TAG['name']('a', 'b', c='d')}}
``:code
If the TAG object is created with an empty name, it can be used to concatenate multiple strings and HTML helpers together without inserting them into a surrounding tag, but this use is deprecated. Use the ``CAT`` helper instead.
Notice that ``TAG`` is an object, and ``TAG.name`` or ``TAG['name']`` is a function that returns a temporary helper class.
##### ``MENU``
``MENU``:inxx
The MENU helper takes a list of lists or of tuples of the form of ``response.menu`` (as described in Chapter 4) and generates a tree-like structure using unordered lists representing the menu. For example:
``
>>> print MENU([['One', False, 'link1'], ['Two', False, 'link2']])
<ul class="web2py-menu web2py-menu-vertical">
<li><a href="link1">One</a></li>
<li><a href="link2">Two</a></li>
</ul>
``:code
+------
+The third item in each list/tuple can be an HTML helper (which could include nested helpers), and the ``MENU`` helper will simply render that helper rather than creating its own ``<a>`` tag.
+------
+
Each menu item can have a fourth argument that is a nested submenu (and so on recursively):
``
>>> print MENU([['One', False, 'link1', [['Two', False, 'link2']]]])
<ul class="web2py-menu web2py-menu-vertical">
<li class="web2py-menu-expand">
<a href="link1">One</a>
<ul class="web2py-menu-vertical">
<li><a href="link2">Two</a></li>
</ul>
</li>
</ul>
``:code
A menu item can also have an optional 5th element, which is a boolean. When false, the menu item is ignored by the MENU helper.
The MENU helper takes the following optional arguments:
- ``_class``: defaults to "web2py-menu web2py-menu-vertical" and sets the class of the outer UL elements.
- ``ul_class``: defaults to "web2py-menu-vertical" and sets the class of the inner UL elements.
- ``li_class``: defaults to "web2py-menu-expand" and sets the class of the inner LI elements.
If the value of an attribute is specified using a name argument, it can be a str
>>> a = DIV(SPAN('a', _id='test123'), DIV('b', _class='c2'))
>>> d = a.elements('span', _id=re.compile('test\d{3}')
``:code
A special named argument of the DIV (and derived) helpers is ``find``. It can be used to specify a search value or a search regular expression in the text content of the tag. For example:
``
>>> a = DIV(SPAN('abcde'), DIV('fghij'))
>>> d = a.elements(find='bcd')
>>> print d[0]
<span>abcde</span>
``:code
or
``
>>> a = DIV(SPAN('abcde'), DIV('fghij'))
>>> d = a.elements(find=re.compile('fg\w{3}'))
>>> print d[0]
<div>fghij</div>
``:code
#### ``components`` ``components``:inxx
Here's an example of listing all elements in an html string:
``
html = TAG('<a>xxx</a><b>yyy</b>')
for item in html.components: print item
``:code
+``parent``:inxx ``sibling``Linxx
+
+#### ``parent`` and ``siblings``
``parent`` returns the parent of the current element.
``
>>> a = DIV(SPAN('a'),DIV('b'))
+>>> s = a.element('span')
+>>> d = s.parent
>>> d['_class']='abc'
>>> print a
<div class="abc"><span>a</span><div>b</div></div>
+>>> for e in s.siblings(): print e
+<div>b</div>
``:code
#### ``flatten`` ``flatten``:inxx
-web2py uses ``{{ ... }}`` to escape Python code embedded in HTML. The advantage of using curly brackets instead of angle brackets is that it's transparent to all common HTML editors. This allows the developer to use those editors to create web2py views.
Since the developer is embedding Python code into HTML, the document should be indented according to HTML rules, and not Python rules. Therefore, we allow unindented Python inside the ``{{ ... }}`` tags. Since Python normally uses indentation to delimit blocks of code, we need a different way to delimit them; this is why the web2py template language makes use of the Python keyword ``pass``.
-------
A code block starts with a line ending with a colon and ends with a line beginning with ``pass``. The keyword ``pass`` is not necessary when the end of the block is obvious from the context.
-------
Here is an example:
``
{{
if i == 0:
response.write('i is 0')
else:
response.write('i is not 0')
pass
}}
``:code
Note that ``pass`` is a Python keyword, not a web2py keyword. Some Python editors, such as Emacs, use the keyword ``pass`` to signify the division of blocks and use it to re-indent code automatically.
An equivalent syntax is:
``
{{=TAG['name']('a', 'b', c='d')}}
``:code
If the TAG object is created with an empty name, it can be used to concatenate multiple strings and HTML helpers together without inserting them into a surrounding tag, but this use is deprecated. Use the ``CAT`` helper instead.
Notice that ``TAG`` is an object, and ``TAG.name`` or ``TAG['name']`` is a function that returns a temporary helper class.
##### ``MENU``
``MENU``:inxx
The MENU helper takes a list of lists or of tuples of the form of ``response.menu`` (as described in Chapter 4) and generates a tree-like structure using unordered lists representing the menu. For example:
``
>>> print MENU([['One', False, 'link1'], ['Two', False, 'link2']])
<ul class="web2py-menu web2py-menu-vertical">
<li><a href="link1">One</a></li>
<li><a href="link2">Two</a></li>
</ul>
``:code
Each menu item can have a fourth argument that is a nested submenu (and so on recursively):
``
>>> print MENU([['One', False, 'link1', [['Two', False, 'link2']]]])
<ul class="web2py-menu web2py-menu-vertical">
<li class="web2py-menu-expand">
<a href="link1">One</a>
<ul class="web2py-menu-vertical">
<li><a href="link2">Two</a></li>
</ul>
</li>
</ul>
``:code
A menu item can also have an optional 5th element, which is a boolean. When false, the menu item is ignored by the MENU helper.
The MENU helper takes the following optional arguments:
- ``_class``: defaults to "web2py-menu web2py-menu-vertical" and sets the class of the outer UL elements.
- ``ul_class``: defaults to "web2py-menu-vertical" and sets the class of the inner UL elements.
- ``li_class``: defaults to "web2py-menu-expand" and sets the class of the inner LI elements.
If the value of an attribute is specified using a name argument, it can be a str
>>> a = DIV(SPAN('a', _id='test123'), DIV('b', _class='c2'))
>>> d = a.elements('span', _id=re.compile('test\d{3}')
``:code
A special named argument of the DIV (and derived) helpers is ``find``. It can be used to specify a search value or a search regular expression in the text content of the tag. For example:
``
>>> a = DIV(SPAN('abcde'), DIV('fghij'))
>>> d = a.elements(find='bcd')
>>> print d[0]
<span>abcde</span>
``:code
or
``
>>> a = DIV(SPAN('abcde'), DIV('fghij'))
>>> d = a.elements(find=re.compile('fg\w{3}'))
>>> print d[0]
<div>fghij</div>
``:code
#### ``components``
Here's an example of listing all elements in an html string:
``
html = TAG('<a>xxx</a><b>yyy</b>')
for item in html.components: print item
``:code
-#### ``parent``
``parent`` returns the parent of the current element.
``
>>> a = DIV(SPAN('a'),DIV('b'))
->>> d = a.element('a').parent()
>>> d['_class']='abc'
>>> print a
<div class="abc"><span>a</span><div>b</div></div>
``:code
#### ``flatten``

- It is written in HTML5 and uses the "modernizr" ``modernizr``:cite library for backward compatibility. The actual layout include some extra conditional statements required by IE and they are omitted for brevity.
- It displays both ``response.title`` and ``response.subtitle`` which can be set in a model. If they are not set, it adopts the application name as title
- It includes the ``web2py_ajax.html`` file in the header which generated all the link and script import statements.
+- It uses a modified version of "skeleton" ``skeleton``:cite a library for flexible layouts which works on mobile devices and re-arranges columns to fit small screens.
+- It uses "superfish.js" ``superfish``:cite for dynamic cascading menus. There is an explicit script to activate the superfish cascading menu and it can be removed if not necessary.
- The ``{{=auth.navbar(...)}}`` displays a welcome to the current user and links to auth functions like login, logout, register, change password, etc. depending on context. It is a helper factory and its output can be manipulated as any other helper. It is placed in a ``{{try:}}...{{except:pass}}`` in case auth is undefined.
- The ``{{=MENU(response.menu)`` displays the menu structure as ``<ul>...</ul>``.
- ``{{include}}`` is replaced by the content of the extending view when the page is rendered.
- By default it uses a conditional three column (the left and right sidebars can be turned off by the extending views)
- It uses the following classes: header, main, footer
- It contains the following blocks: statusbar, left_sidebar, center, right_sidebar, footer.
Views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
``CSS``:inxx
Customizing the default layout without editing is very easy because the CSS files are documented:
- "bootstrap.min.css" contains the Twitter Boostrap CSS style ``bootstrap``:cite ``Bootstrap``:inxx
- "web2py.css" contains web2py specific styles
- It is written in HTML5 and uses the "modernizr" ``modernizr``:cite library for backward compatibility. The actual layout include some extra conditional statements required by IE and they are omitted for brevity.
- It displays both ``response.title`` and ``response.subtitle`` which can be set in a model. If they are not set, it adopts the application name as title
- It includes the ``web2py_ajax.html`` file in the header which generated all the link and script import statements.
-- It uses a modified version of "skeleton" ``skeleton``:cite a library for flexible layouts which works on mobile devices and re-arranges columns to fit small screened.
-- It uses "superfish.js" for dynamic cascading menus. There is an explicit script to activate the superfish cascading menu and it can be removed if not necessary.
- The ``{{=auth.navbar(...)}}`` displays a welcome to the current user and links to auth functions like login, logout, register, change password, etc. depending on context. It is a helper factory and its output can be manipulated as any other helper. It is placed in a ``{{try:}}...{{except:pass}}`` in case auth is undefined.
- The ``{{=MENU(response.menu)`` displays the menu structure as ``<ul>...</ul>``.
- ``{{include}}`` is replaced by the content of the extending view when the page is rendered.
- By default it uses a conditional three column (the left and right sidebars can be turned off by the extending views)
- It uses the following classes: header, main, footer
- It contains the following blocks: statusbar, left_sidebar, center, right_sidebar, footer.
Views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
``CSS``:inxx
Customizing the default layout without editing is very easy because the CSS files are documented:
- "bootstrap.min.css" contains the Twitter Boostrap CSS style ``Bootstrap``:inxx
- "web2py.css" contains web2py specific styles

Notice that the decorator must be imported before using it in a controller.
When the "index" function is called from a regular browser (desktop computer), web2py will render the returned dictionary using the view "[controller]/index.html". However, when it is called by a mobile device, the dictionary will be rendered by "[controller]/index.mobile.html". Notice that mobile views have the "mobile.html" extension.
Notice that the decorator must be important once before using it in a controller.
When the "index" function is called from a regular browser (desktop computer), web2py will render the returned dictionary using the view "[controller]/index.html". However, when it is called by a mobile device, the dictionary will be rendered by "[controller]/index.mobile.html". Notice that mobile views have the "mobile.html" extension.

The A helper takes a special argument called ``cid``. It works as follows:
``
{{=A('linked page', _href='http://example.com', cid='myid')}}
<div id="myid"></div>
``:code
and a click on the link causes the content to be loaded in the div. This is similar but more powerful than the above syntax since it is designed to refresh page components. We discuss applications of ``cid`` in more detail in Chapter 12, in the context of components.
These ajax features require jQuery and "static/js/web2py_ajax.js", which are automatically included by placing ``{{include 'web2py_ajax.html'}}`` in the layout head. "views/web2py_ajax.html" defines some variables based on ``request`` and includes all necessary js and css files.
##### ``B``
``B``:inxx
This helper makes its contents bold.
``
>>> print B('<hello>', XML('<i>world</i>'), _class='test', _id=0)
<b id="0" class="test">&lt;hello&gt;<i>world</i></b>
``:code
Here is a basic syntax primer:
--------------------------------------------------
**SOURCE** | **OUTPUT**
``# title`` | **title**
``## section`` | **section**
``### subsection`` | **subsection**
``**bold**`` | **bold**
``''italic''`` | ''italic''
``!`!`verbatim`!`!`` | ``verbatim``
``http://google.com`` | http://google.com
``http://...`` | ``<a href="http://...">http:...</a>``
``http://...png`` | ``<img src="http://...png" />``
``http://...mp3`` | ``<audio src="http://...mp3"></audio>``
``http://...mp4`` | ``<video src="http://...mp4"></video>``
``qr:http://...`` | ``<a href="http://..."><img src="qr code"/></a>``
``embed:http://...`` | ``<iframe src="http://..."></iframe>``
``[[click me #myanchor]]`` | [[click me #myanchor]]
``$````$\int_a^b sin(x)dx$````$`` | $$\int_a^b sin(x)dx$$
---------------------------------------------------
Simply including a link to an image, a videos or an audio files without markup result in the corresponding image, video or audio file being included automatically (for audio and video it uses html <audio> and <video> tags).
Adding a link with the ``qr:`` prefix such as
``
qr:http://web2py.com
``
results in the corresponding QR code being embedded and linking the said URL.
Adding a link with the ``embed:`` prefix such as
``
embed:http://www.youtube.com/embed/x1w8hKTJ2Co
``
results in the page being embedded, in this case a youtube video is embedded.
Images can also be embedded with the following syntax:
``
[[image-description http://.../image.png right 200px]]
``
Unordered lists with:
``
- one
- two
- three
``
Each menu item can have a fourth argument that is a nested submenu (and so on re
>>> print MENU([['One', False, 'link1', [['Two', False, 'link2']]]])
<ul class="web2py-menu web2py-menu-vertical">
<li class="web2py-menu-expand">
<a href="link1">One</a>
<ul class="web2py-menu-vertical">
<li><a href="link2">Two</a></li>
</ul>
</li>
</ul>
``:code
A menu item can also have an optional 5th element, which is a boolean. When false, the menu item is ignored by the MENU helper.
The MENU helper takes the following optional arguments:
- ``_class``: defaults to "web2py-menu web2py-menu-vertical" and sets the class of the outer UL elements.
- ``ul_class``: defaults to "web2py-menu-vertical" and sets the class of the inner UL elements.
- ``li_class``: defaults to "web2py-menu-expand" and sets the class of the inner LI elements.
``mobile``:inxx
``MENU`` takes an optional argument ``mobile``. When set to ``True`` instead of building a recursive ``UL`` menu structure it returns a ``SELECT`` dropdown with all the menu options and a ``onchange`` attribute that redirects to the page corresponding to the selected option. This is designed an an alternative menu representation that increases usability on small mobile devices such as phones.
Normally the menu is used in a layout with the following syntax:
``
{{=MENU(response.menu, mobile=request.user_agent().is_mobile)}}
``
In this way a mobile device is automatically detected and the menu is rendered accordingly.
### ``BEAUTIFY``
``BEAUTIFY`` is used to build HTML representations of compound objects, including lists, tuples and dictionaries:
``
{{=BEAUTIFY({"a": ["hello", XML("world")], "b": (1, 2)})}}
``:code
``BEAUTIFY`` returns an XML-like object serializable to XML, with a nice looking representation of its constructor argument. In this case, the XML representation of:
``
{"a": ["hello", XML("world")], "b": (1, 2)}
``:code
will render as:
not Python commands.
Any content or code that precedes the ``{{extend ...}}`` directive will be inserted (and therefore executed) before the beginning of the extended view's content/code. Although this is not typically used to insert actual HTML content before the extended view's content, it can be useful as a means to define variables or functions that you want to make available to the extended view. For example, consider a view "index.html":
``
{{sidebar_enabled=True}}
{{extend 'layout.html'}}
<h1>Home Page</h1>
``:code
and an excerpt from "layout.html":
``
{{if sidebar_enabled:}}
<div id="sidebar">
Sidebar Content
</div>
{{pass}}
``:code
Because the ``sidebar_enabled`` assignment in "index.html" comes before the ``extend``, that line gets inserted before the beginning of "layout.html", making ``sidebar_enabled`` available anywhere within the "layout.html" code (a somewhat more sophisticated version of this is used in the **welcome** app).
It is also worth pointing out that the variables returned by the controller function are available not only in the function's main view, but in all of its extended and included views as well.
The argument of an ``extend`` or ``include`` (i.e., the extended or included view name) can be a python variable (though not a python expression). However, this imposes a limitation -- views that use variables in ``extend`` or ``include`` statements cannot be bytecode compiled. As noted above, bytecode-compiled views include the entire tree of extended and included views, so the specific extended and included views must be known at compile time, which is not possible if the view names are variables (whose values are not determined until run time). Because bytecode compiling views can provide a significant speed boost, using variables in ``extend`` and ``include`` should generally be avoided if possible.
In some cases, an alternative to using a variable in an ``include`` is simply to place regular ``{{include ...}}`` directives inside an ``if...else`` block.
``
{{if some_condition:}}
{{include 'this_view.html'}}
{{else:}}
{{include 'that_view.html'}}
{{pass}}
``:code
The above code does not present any problem for bytecode compilation because no variables are involved. Note, however, that the bytecode compiled view will actually include the Python code for both "this_view.html" and "that_view.html", though only the code for one of those views will be executed, depending on the value of ``some_condition``.
Keep in mind, this only works for ``include`` -- you cannot place ``{{extend ...}}`` directives inside ``if...else`` blocks.
``response.menu``:inxx ``menu``:inxx ``response.meta``:inxx ``meta``:inxx
Layouts are used to encapsulate page commonality (headers, footers, menus), and though they are not mandatory, they will make your application easier to write and maintain. In particular, we suggest writing layouts that take advantage of the following variables that can be set in the controller. Using these well known variables will help make your layouts interchangeable:
``
response.title
Below is the "views/layout.html" that ships with the web2py scaffolding applicat
</a>
</div>
</div>
{{end}}
</div>
</div><!-- container -->
</div><!-- footer -->
</body>
</html>
``:code
There are a few features of this default layout that make it very easy to use and customize:
- It is written in HTML5 and uses the "modernizr" ``modernizr``:cite library for backward compatibility. The actual layout include some extra conditional statements required by IE and they are omitted for brevity.
- It displays both ``response.title`` and ``response.subtitle`` which can be set in a model. If they are not set, it adopts the application name as title
- It includes the ``web2py_ajax.html`` file in the header which generated all the link and script import statements.
- It uses a modified version of "skeleton" ``skeleton``:cite a library for flexible layouts which works on mobile devices and re-arranges columns to fit small screened.
- It uses "superfish.js" for dynamic cascading menus. There is an explicit script to activate the superfish cascading menu and it can be removed if not necessary.
- The ``{{=auth.navbar(...)}}`` displays a welcome to the current user and links to auth functions like login, logout, register, change password, etc. depending on context. It is a helper factory and its output can be manipulated as any other helper. It is placed in a ``{{try:}}...{{except:pass}}`` in case auth is undefined.
- The ``{{=MENU(response.menu)`` displays the menu structure as ``<ul>...</ul>``.
- ``{{include}}`` is replaced by the content of the extending view when the page is rendered.
- By default it uses a conditional three column (the left and right sidebars can be turned off by the extending views)
- It uses the following classes: header, main, footer
- It contains the following blocks: statusbar, left_sidebar, center, right_sidebar, footer.
Views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
Customizing the default layout without editing is very easy because the CSS file
To change colors and background images,
try append the following code to layout.html header:
``
<style>
body { background: url('images/background.png') repeat-x #3A3A3A; }
a { color: #349C01; }
.header h1 { color: #349C01; }
.header h2 { color: white; font-style: italic; font-size: 14px;}
.statusbar { background: #333333; border-bottom: 5px #349C01 solid; }
.statusbar a { color: white; }
.footer { border-top: 5px #349C01 solid; }
</style>
``:code
Of course you can also completely replace the "layout.html" and "web2py.css" files with your own.
#### Mobile development
The default layout.html is designed to be friendly to mobile devices but that is not enough. One may need to use different views when a page is visited by a mobile device.
Tha A helper takes a special argument called ``cid``. It works as follows:
``
{{=A('linked page', _href='http://example.com', cid='myid')}}
<div id="myid"></div>
``:code
and a click on the link causes the content to be loaded in the div. This is similar but more powerful than the above syntax since it is designed to refresh page components. We discuss applications of ``cid`` in more detail in Chapter 12, in the context of components.
These ajax features require jQuery and "static/js/web2py_ajax.js", which are automatically included by placing ``{{include 'web2py_ajax.html'}}`` in the layout head. "views/web2py_ajax.html" defines some variables based on ``request`` and includes all necessary js and css files.
##### ``B``
``B``:inxx
This helper makes its contents bold.
``
>>> print B('<hello>', XML('<i>world</i>'), _class='test', _id=0)
<b id="0" class="test">&lt;hello&gt;<i>world</i></b>
``:code
Here is a basic syntax primer:
--------------------------------------------------
**SOURCE** | **OUTPUT**
``# title`` | **title**
``## section`` | **section**
``### subsection`` | **subsection**
``**bold**`` | **bold**
``''italic''`` | ''italic''
``!`!`verbatim`!`!`` | ``verbatim``
``http://google.com`` | http://google.com
``http://...`` | ``<a href="http://...">http:...</a>``
``http://...png`` | ``<img src="http://...png" />``
``http://...mp3`` | ``<audio src="http://...mp3"></audio>``
``http://...mp4`` | ``<video src="http://...mp4"></video>``
``qr:http://...`` | ``<a href="http://..."><img src="qr code"/></a>``
``embed:http://...`` | ``<iframe src="http://..."></iframe>``
``[[click me #myanchor]]`` | [[click me #myanchor]]
``$````$\int_a^b sin(x)dx$````$`` | $$\int_a^b sin(x)dx$$
---------------------------------------------------
Simply including a link to an image, a videos or an audio files without markup result in the corresponding image, video or audio file beling included automatically (for audio and video it uses html <audio> and <video> tags).
Adding a link with the ``qr:`` prefix such as
``
qr:http://web2py.com
``
results in the corresponding QR code being embedded and linking the said URL.
Adding a link tith the ``embed:`` prefix such as
``
embed:http://www.youtube.com/embed/x1w8hKTJ2Co
``
results in the page being embedded, in this case a youtube video is embedded.
Images can also be embedded with the following syntax:
``
[[image-description http://.../image.png right 200px]]
``
Unordered lists with:
``
- one
- two
- three
``
Each menu item can have a fourth argument that is a nested submenu (and so on re
>>> print MENU([['One', False, 'link1', [['Two', False, 'link2']]]])
<ul class="web2py-menu web2py-menu-vertical">
<li class="web2py-menu-expand">
<a href="link1">One</a>
<ul class="web2py-menu-vertical">
<li><a href="link2">Two</a></li>
</ul>
</li>
</ul>
``:code
A menu item can also have an optional 5th element, which is a boolean. When false, the menu item is ignored by the MENU helper.
The MENU helper takes the following optional arguments:
- ``_class``: defaults to "web2py-menu web2py-menu-vertical" and sets the class of the outer UL elements.
- ``ul_class``: defaults to "web2py-menu-vertical" and sets the class of the inner UL elements.
- ``li_class``: defaults to "web2py-menu-expand" and sets the class of the inner LI elements.
``mobile``:inxx
``MENU`` takes an optional argument ``mobile``. When set to ``True`` instead of building a recursive ``UL`` menu structure it returns a ``SELECT`` dropdown with all the menu options and a ``onchange`` attribute that redirects to the page corresponding to the selected option. This is designed an an alterantive menu representation that increases usability on small mobile devices such as phones.
Normally the menu is used in a layout with the following syntax:
``
{{=MENU(response.menu, mobile=request.user_agent().is_mobile)}}
``
In this way a mobile device is automatically detected and the menu is rendered accordingly.
### ``BEAUTIFY``
``BEAUTIFY`` is used to build HTML representations of compound objects, including lists, tuples and dictionaries:
``
{{=BEAUTIFY({"a": ["hello", XML("world")], "b": (1, 2)})}}
``:code
``BEAUTIFY`` returns an XML-like object serializable to XML, with a nice looking representation of its constructor argument. In this case, the XML representation of:
``
{"a": ["hello", XML("world")], "b": (1, 2)}
``:code
will render as:
not Python commands.
Any content or code that precedes the ``{{extend ...}}`` directive will be inserted (and therefore executed) before the beginning of the extended view's content/code. Although this is not typically used to insert actual HTML content before the extended view's content, it can be useful as a means to define variables or functions that you want to make available to the extended view. For example, consider a view "index.html":
``
{{sidebar_enabled=True}}
{{extend 'layout.html'}}
<h1>Home Page</h1>
``:code
and an excerpt from "layout.html":
``
{{if sidebar_enabled:}}
<div id="sidebar">
Sidebar Content
</div>
{{pass}}
``:code
Because the ``sidebar_enabled`` assignment in "index.html" comes before the ``extend``, that line gets inserted before the beginning of "layout.html", making ``sidebar_enabled`` available anywhere within the "layout.html" code (a somewhat more sophisticated version of this is used in the **welcome** app).
It is also worth pointing out that the variables returned by the controller function are available not only in the function's main view, but in all of its extended and included views as well.
The argument of an ``extend`` or ``include`` (i.e., the extended or included view name) can be a python variable (though not a python expression). However, this imposes a limitation -- views that use variables in ``extend`` or ``include`` statements cannot be bytecode compiled. As noted above, bytecode compiled views include the entire tree of extended and included views, so the specific extended and included views must be known at compile time, which is not possible if the view names are variables (whose values are not determined until run time). Because bytecode compiling views can provide a significant speed boost, using variables in ``extend`` and ``include`` should generally be avoided if possible.
In some cases, an alternative to using a variable in an ``include`` is simply to place regular ``{{include ...}}`` directives inside an ``if...else`` block.
``
{{if some_condition:}}
{{include 'this_view.html'}}
{{else:}}
{{include 'that_view.html'}}
{{pass}}
``:code
The above code does not present any problem for bytecode compilation because no variables are involved. Note, however, that the bytecode compiled view will actually include the Python code for both "this_view.html" and "that_view.html", though only the code for one of those views will be executed, depending on the value of ``some_condition``.
Keep in mind, this only works for ``include`` -- you cannot place ``{{extend ...}}`` directives inside ``if...else`` blocks.
``response.menu``:inxx ``menu``:inxx ``response.meta``:inxx ``meta``:inxx
Layouts are used to encapsulate page commonality (headers, footers, menus), and though they are not mandatory, they will make your application easier to write and maintain. In particular, we suggest writing layouts that take advantage of the following variables that can be set in the controller. Using these well known variables will help make your layouts interchangeable:
``
response.title
Below is the "views/layout.html" that ships with the web2py scaffolding applicat
</a>
</div>
</div>
{{end}}
</div>
</div><!-- container -->
</div><!-- footer -->
</body>
</html>
``:code
There are a few features of this default layout that make it very easy to use and customize:
- It is written in HTML5 and uses the "modernizr" ``modernizr``:cite library for backward compatibility. The actual layout include some extra conditional statements required by IE and they are omitted for brevity.
- It displays both ``response.title`` and ``response.subtitle`` which can be set in a model. If they are not set, it adopts the application name as title
- It includes the ``web2py_ajax.html`` file in the header which generated all the link and script import statements.
- It uses a modified version of "skeleton" ``skeleton``:cite a library for flexible layouts which works on mobile devices and re-arranges columns to fit small screened.
- It uses "superfish.js" for dynamic cascading menus. There is an explicit script to activate the superfish cascading menu and it can be removed if not necessary.
- The ``{{=auth.navbar(...)}}`` displays a welcome to the current user and links to auth functions like login, logout, register, change password, etc. depending on context. It is a heler factory and its output can be manipulated as any other helper. It is placed in a ``{{try:}}...{{except:pass}}`` in case auth is undefined.
- The ``{{=MENU(response.menu)`` displays the menu structure as ``<ul>...</ul>``.
- ``{{include}}`` is replaced by the content of the extending view when the page is rendered.
- By default it uses a conditional three column (the left and right sidebars can be turned off by the extending views)
- It uses the following classes: header, main, footer
- It contains the following blocks: statusbar, left_sidebar, center, right_sidebar, footer.
Views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
Customizing the default layout without editing is very easy because the CSS file
To change colors and background images,
try append the following code to layout.html header:
``
<style>
body { background: url('images/background.png') repeat-x #3A3A3A; }
a { color: #349C01; }
.header h1 { color: #349C01; }
.header h2 { color: white; font-style: italic; font-size: 14px;}
.statusbar { background: #333333; border-bottom: 5px #349C01 solid; }
.statusbar a { color: white; }
.footer { border-top: 5px #349C01 solid; }
</style>
``:code
Of course you can also completely replace the "layout.html" and "web2py.css" files with your own.
#### Mobile development
The default layout.html is designed to be friendly to mobile devices but that is not enought. One may need to use different views when a page is visited by a mobile device.

+A menu item can also have an optional 5th element, which is a boolean. When false, the menu item is ignored by the MENU helper.
+
The MENU helper takes the following optional arguments:
- ``_class``: defaults to "web2py-menu web2py-menu-vertical" and sets the class of the outer UL elements.
- ``ul_class``: defaults to "web2py-menu-vertical" and sets the class of the inner UL elements.
- ``li_class``: defaults to "web2py-menu-expand" and sets the class of the inner LI elements.
``mobile``:inxx
``MENU`` takes an optional argument ``mobile``. When set to ``True`` instead of building a recursive ``UL`` menu structure it returns a ``SELECT`` dropdown with all the menu options and a ``onchange`` attribute that redirects to the page corresponding to the selected option. This is designed an an alterantive menu representation that increases usability on small mobile devices such as phones.
Normally the menu is used in a layout with the following syntax:
``
{{=MENU(response.menu, mobile=request.user_agent().is_mobile)}}
``
In this way a mobile device is automatically detected and the menu is rendered accordingly.
### ``BEAUTIFY``
``BEAUTIFY`` is used to build HTML representations of compound objects, including lists, tuples and dictionaries:
``
There are a few features of this default layout that make it very easy to use an
Views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
``CSS``:inxx
Customizing the default layout without editing is very easy because the CSS files are documented:
- "bootstrap.min.css" contains the Twitter Boostrap CSS style ``Bootstrap``:inxx
- "web2py.css" contains web2py specific styles
+To change colors and background images,
+try append the following code to layout.html header:
``
+<style>
body { background: url('images/background.png') repeat-x #3A3A3A; }
a { color: #349C01; }
.header h1 { color: #349C01; }
.header h2 { color: white; font-style: italic; font-size: 14px;}
.statusbar { background: #333333; border-bottom: 5px #349C01 solid; }
.statusbar a { color: white; }
.footer { border-top: 5px #349C01 solid; }
+</style>
``:code
Of course you can also completely replace the "layout.html" and "web2py.css" files with your own.
The MENU helper takes the following optional arguments:
- ``_class``: defaults to "web2py-menu web2py-menu-vertical" and sets the class of the outer UL elements.
- ``ul_class``: defaults to "web2py-menu-vertical" and sets the class of the inner UL elements.
- ``li_class``: defaults to "web2py-menu-expand" and sets the class of the inner LI elements.
``mobile``:inxx
``MENU`` takes an optional argument ``mobile``. When set to ``True`` instead of building a recursive ``UL`` menu structure it returns a ``SELECT`` dropdown with all the menu options and a ``onchange`` attribute that redirects to the page corresponding to the selected option. This is designed an an alterantive menu representation that increases usability on small mobile devices such as phones.
Normally the menu is used in a layout with the following syntax:
``
{{=MENU(response.menu, mobile=request.user_agent().is_mobile)}}
``
In this way a mobile device is automatically detected and the menu is rendered accordingly.
### ``BEAUTIFY``
``BEAUTIFY`` is used to build HTML representations of compound objects, including lists, tuples and dictionaries:
``
There are a few features of this default layout that make it very easy to use an
Views can turn on and fill sidebars as follows:
``
{{left_sidebar_enable=True}}
{{extend 'layout.html'}}
This text goes in center
{{block left_sidebar}}
This text goes in sidebar
{{end}}
``:code
#### Customizing the default layout
``CSS``:inxx
Customizing the default layout without editing is very easy because the CSS files are documented:
- "skeleton.css" contains reset, grid layout and form styles
- "web2py.css" contains web2py specific styles
-- "superfish.css" contains menu styles
-To change colors and background images, simply append the following code to "web2py.css":
``
body { background: url('images/background.png') repeat-x #3A3A3A; }
a { color: #349C01; }
.header h1 { color: #349C01; }
.header h2 { color: white; font-style: italic; font-size: 14px;}
.statusbar { background: #333333; border-bottom: 5px #349C01 solid; }
.statusbar a { color: white; }
.footer { border-top: 5px #349C01 solid; }
``:code
-The menu is built in a color-neutral way but you can change that too.
-
Of course you can also completely replace the "layout.html" and "web2py.css" files with your own.