Built-in helpers
A
This helper is used to build links.
>>> print A('<click>', XML('<b>me</b>'),
_href='http://www.web2py.com')
<a href='http://www.web2py.com'><click><b>me</b></a>
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')}}
<div id="t"><div>
and the response of the ajax callback will replace the content (inner HTML) of the DIV with id equal to “t”.
<div id="b">{{=A('click me', callback=URL('myaction'), delete='div#b')}}</div>
and upon response, the closest tag matching “div#b” will be deleted. In this case, the whole DIV with the link will be deleted.
A typical application is:
{{=A('click me', callback=URL('myaction'), delete='tr')}}
in a table. Using the link will perform the callback and delete the table row.
target
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>
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.
ASSIGNJS
ASSIGNJS allows a server-side value to be used as a client-side javascript value.
For instance, if in a controller you write
return dict(stra='abcd', obj=alist)
and in a view write
<script>
{{=ASSIGNJS(o=obj)}}
...
Then the javascript variable o will have the value passed in obj, which is alist.
A further example is shown below under Javascript In Views.
B
This helper makes its contents bold.
>>> print B('<hello>', XML('<i>world</i>'), _class='test', _id=0)
<b id="0" class="test"><hello><i>world</i></b>
BODY
This helper makes the body of a page.
>>> print BODY('<hello>', XML('<b>world</b>'), _bgcolor='red')
<body bgcolor="red"><hello><b>world</b></body>
BR
This helper creates a line break.
>>> print BR()
<br />
Notice that helpers can be repeated using the multiplication operator:
>>> print BR()*5
<br /><br /><br /><br /><br />
CAT
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>.
CENTER
This helper centers its content.
>>> print CENTER('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<center id="0" class="test"><hello><b>world</b></center>
CODE
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 style="vertical-align:top;">
<td style="min-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;
color: #A0A0A0;
">1.</pre></td><td><pre style="
font-size: 11px;
font-family: Bitstream Vera Sans Mono,monospace;
background-color: transparent;
margin: 0;
padding: 5px;
border: none;
overflow: auto;
white-space: pre !important;
"><span style="color:#185369; font-weight: bold">print </span>
<span style="color: #FF9966">"hello"</span></pre></td></tr></table>
Here is a similar example for HTML
>>> print CODE('<html><body>{{=request.env.remote_add}}</body></html>',
... language='html')
<table>...<code>...
<html><body>{{=request.env.remote_add}}</body></html>
...</code>...</table>
These are the default arguments for the CODE
helper:
CODE("print 'hello world'", language='python', link=None, counter=1, styles={})
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;'})
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
>>> print COL('a', 'b')
<col>ab</col>
COLGROUP
>>> print COLGROUP('a', 'b')
<colgroup>ab</colgroup>
DIV
All helpers apart from XML
are derived from DIV
and inherit its basic methods.
>>> print DIV('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<div id="0" class="test"><hello><b>world</b></div>
EM
Emphasizes its content.
>>> print EM('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<em id="0" class="test"><hello><b>world</b></em>
FIELDSET
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>
FORM
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>
The “enctype” is “multipart/form-data” by default.
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>
H1
, H2
, H3
, H4
, H5
, H6
These helpers are for paragraph headings and subheadings:
>>> print H1('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<h1 id="0" class="test"><hello><b>world</b></h1>
HEAD
For tagging the HEAD of an HTML page.
>>> print HEAD(TITLE('<hello>', XML('<b>world</b>')))
<head><title><hello><b>world</b></title></head>
HTML
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] .
>>> 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><hello><b>world</b></body></html>
The HTML helper also takes some additional optional arguments that have the following default:
HTML(..., lang='en', doctype='transitional')
where doctype can be ‘strict’, ‘transitional’, ‘frameset’, ‘html5’, or a full doctype string.
XHTML
XHTML is similar to HTML but it creates an XHTML doctype instead.
XHTML(..., lang='en', doctype='transitional', xmlns='http://www.w3.org/1999/xhtml')
where doctype can be ‘strict’, ‘transitional’, ‘frameset’, or a full doctype string.
HR
This helper creates a horizontal line in an HTML page
>>> print HR()
<hr />
I
This helper makes its contents italic.
>>> print I('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<i id="0" class="test"><hello><b>world</b></i>
IFRAME
This helper includes another web page in the current page. The url of the other page is specified via the “_src” attribute.
>>> print IFRAME(_src='http://www.web2py.com')
<iframe src="http://www.web2py.com"></iframe>
IMG
It can be used to embed images into HTML:
>>> print IMG(_src='http://example.com/image.png', _alt='test')
<img src="http://example.com/image.ong" alt="rest" />
Here is a combination of A, IMG, and URL helpers for including a static image with a link:
>>> print 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>
INPUT
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" />
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" />
For radio buttons, INPUT
selectively sets the “checked” attribute:
>>> 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
and similarly for checkboxes:
>>> 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" />
LABEL
It is used to create a LABEL tag for an INPUT field.
>>> print LABEL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<label id="0" class="test"><hello><b>world</b></label>
LEGEND
It is used to create a legend tag for a field in a form.
>>> print LEGEND('Name', _for='myfield')
<legend for="myfield">Name</legend>
LI
It makes a list item and should be contained in a UL
or OL
tag.
>>> print LI('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<li id="0" class="test"><hello><b>world</b></li>
META
To be used for building META
tags in the HTML
head. For example:
>>> print META(_name='security', _content='high')
<meta name="security" content="high" />
MARKMIN
Implements the markmin wiki syntax. It converts the input text into output html according to the markmin rules described in the example below:
>>> 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>
The markmin syntax is described in gluon/contrib/markmin/markmin.html that ships with web2py.
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 markmin2html(m)
from gluon.contrib.markmin.markmin2latex import markmin2latex
print markmin2latex(m)
from gluon.contrib.markmin.markmin2pdf import markmin2pdf
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 |
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]] | Creating an anchor for a link |
$ $\int_a^b sin(x)dx$ $ |
MARKMIN links
Links take this form:
[[link display text <link>]]
where can be:
- an anchor (e.g.
#myanchor
), - an URI (e.g.
http://www.web2py.com
), or - a relative reference (like in
[[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
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("``abab``:custom", extra=dict(custom=lambda text: text.replace('a', 'c'))
generates
'cbcb'
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.
>>> print OBJECT('<hello>', XML('<b>world</b>'), _src='http://www.web2py.com')
<object src="http://www.web2py.com"><hello><b>world</b></object>
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.
>>> print OL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<ol id="0" class="test"><li><hello></li><li><b>world</b></li></ol>
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.
>>> print INPUT(_type='checkbox', _name='test', _checked=ON)
<input checked="checked" type="checkbox" name="test" />
OPTGROUP
Allows you to group multiple options in a SELECT and it is useful to customize the fields using CSS.
>>> 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>
OPTION
This should only be used as part of a SELECT
/OPTION
combination.
>>> print OPTION('<hello>', XML('<b>world</b>'), _value='a')
<option value="a"><hello><b>world</b></option>
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”.
>>> print SELECT('a', 'b', value='b'):
<select>
<option value="a">a</option>
<option value="b" selected="selected">b</option>
</select>
P
This is for tagging a paragraph.
>>> print P('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<p id="0" class="test"><hello><b>world</b></p>
PRE
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"><hello><b>world</b></pre>
SCRIPT
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>
SELECT
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="<hello>"><hello></option>
<option value="<b>world</b>"><b>world</b></option>
</select>
SPAN
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"><hello><b>world</b></span>
STYLE
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>
and here it is linked:
>>> print STYLE(_src='style.css')
<style src="style.css"><!--
//--></style>
TABLE
, TR
, TD
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>
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>
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>
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>
TBODY
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><hello></td></tr></tbody>
TEXTAREA
This helper makes a <textarea>...</textarea>
tag.
>>> print TEXTAREA('<hello>', XML('<b>world</b>'), _class='test')
<textarea class="test" cols="40" rows="10"><hello><b>world</b></textarea>
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"><hello world></textarea>
TFOOT
This is used to tag table footer rows.
>>> print TFOOT(TR(TD('<hello>')), _class='test', _id=0)
<tfoot id="0" class="test"><tr><td><hello></td></tr></tfoot>
TH
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"><hello><b>world</b></th>
THEAD
This is used to tag table header rows.
>>> print THEAD(TR(TH('<hello>')), _class='test', _id=0)
<thead id="0" class="test"><tr><th><hello></th></tr></thead>
TITLE
This is used to tag the title of a page in an HTML header.
>>> print TITLE('<hello>', XML('<b>world</b>'))
<title><hello><b>world</b></title>
TR
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><hello></td><td><b>world</b></td></tr>
TT
Tags text as typewriter (monospaced) text.
>>> print TT('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<tt id="0" class="test"><hello><b>world</b></tt>
UL
Signifies an Unordered List and should contain LI
items. If its content is not tagged as LI
, UL
does it automatically.
>>> print UL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
<ul id="0" class="test"><li><hello></li><li><b>world</b></li></ul>
URL
The URL helper is documented in Chapter 4 URL
embed64
embed64(filename=None, file=None, data=None, extension='image/gif')
encodes the provided (binary) data into base64, it takes the following optional arguments:
filename
: if provided, opens and reads this file in ‘rb’ mode.file
: if provided, reads this file.data
: if provided, uses the provided data.
xmlescape
xmlescape(data, quote=True)
returns an escaped string of the provided data.
>>> print xmlescape('<hello>')
<hello>