Built-in helpers

A

This helper is used to build links.

  1. >>> print A('<click>', XML('<b>me</b>'),
  2. _href='http://www.web2py.com')
  3. <a href='http://www.web2py.com'>&lt;click&gt;<b>me</b></a>

Instead of _href you can pass the URL using the callback argument. For example in a view:

  1. {{=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:

  1. {{=A('click me', callback=URL('myaction'), target='t')}}
  2. <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”.

  1. <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:

  1. {{=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:

  1. {{=A('linked page', _href='http://example.com', cid='myid')}}
  2. <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

  1. {{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

  1. return dict(stra='abcd', obj=alist)

and in a view write

  1. <script>
  2. {{=ASSIGNJS(o=obj)}}
  3. ...

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.

  1. >>> print B('<hello>', XML('<i>world</i>'), _class='test', _id=0)
  2. <b id="0" class="test">&lt;hello&gt;<i>world</i></b>

BODY

This helper makes the body of a page.

  1. >>> print BODY('<hello>', XML('<b>world</b>'), _bgcolor='red')
  2. <body bgcolor="red">&lt;hello&gt;<b>world</b></body>

BR

This helper creates a line break.

  1. >>> print BR()
  2. <br />

Notice that helpers can be repeated using the multiplication operator:

  1. >>> print BR()*5
  2. <br /><br /><br /><br /><br />

CAT

This helper concatenates other helpers, same as TAG[‘’].

  1. >>> print CAT('Here is a ', A('link', _href=URL()), ', and here is some ', B('bold text'), '.')
  2. Here is a <a href="/app/default/index">link</a>, and here is some <b>bold text</b>.

CENTER

This helper centers its content.

  1. >>> print CENTER('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <center id="0" class="test">&lt;hello&gt;<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.

  1. >>> print CODE('print "hello"', language='python').xml()
  1. <table><tr style="vertical-align:top;">
  2. <td style="min-width:40px; text-align: right;"><pre style="
  3. font-size: 11px;
  4. font-family: Bitstream Vera Sans Mono,monospace;
  5. background-color: transparent;
  6. margin: 0;
  7. padding: 5px;
  8. border: none;
  9. color: #A0A0A0;
  10. ">1.</pre></td><td><pre style="
  11. font-size: 11px;
  12. font-family: Bitstream Vera Sans Mono,monospace;
  13. background-color: transparent;
  14. margin: 0;
  15. padding: 5px;
  16. border: none;
  17. overflow: auto;
  18. white-space: pre !important;
  19. "><span style="color:#185369; font-weight: bold">print </span>
  20. <span style="color: #FF9966">"hello"</span></pre></td></tr></table>

Here is a similar example for HTML

  1. >>> print CODE('<html><body>{{=request.env.remote_add}}</body></html>',
  2. ... language='html')
  1. <table>...<code>...
  2. <html><body>{{=request.env.remote_add}}</body></html>
  3. ...</code>...</table>

These are the default arguments for the CODE helper:

  1. 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:

  1. 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

  1. >>> print COL('a', 'b')
  2. <col>ab</col>

COLGROUP

  1. >>> print COLGROUP('a', 'b')
  2. <colgroup>ab</colgroup>

DIV

All helpers apart from XML are derived from DIV and inherit its basic methods.

  1. >>> print DIV('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <div id="0" class="test">&lt;hello&gt;<b>world</b></div>

EM

Emphasizes its content.

  1. >>> print EM('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <em id="0" class="test">&lt;hello&gt;<b>world</b></em>

FIELDSET

This is used to create an input field together with its label.

  1. >>> print FIELDSET('Height:', INPUT(_name='height'), _class='test')
  2. <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.

  1. >>> print FORM(INPUT(_type='submit'), _action='', _method='post')
  2. <form enctype="multipart/form-data" action="" method="post">
  3. <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:

  1. >>> print FORM(hidden=dict(a='b'))
  2. <form enctype="multipart/form-data" action="" method="post">
  3. <input value="b" type="hidden" name="a" /></form>

H1, H2, H3, H4, H5, H6

These helpers are for paragraph headings and subheadings:

  1. >>> print H1('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <h1 id="0" class="test">&lt;hello&gt;<b>world</b></h1>

HEAD

For tagging the HEAD of an HTML page.

  1. >>> print HEAD(TITLE('<hello>', XML('<b>world</b>')))
  2. <head><title>&lt;hello&gt;<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] .

  1. >>> print HTML(BODY('<hello>', XML('<b>world</b>')))
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  3. <html><body>&lt;hello&gt;<b>world</b></body></html>

The HTML helper also takes some additional optional arguments that have the following default:

  1. 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.

  1. 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

  1. >>> print HR()
  2. <hr />

I

This helper makes its contents italic.

  1. >>> print I('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <i id="0" class="test">&lt;hello&gt;<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.

  1. >>> print IFRAME(_src='http://www.web2py.com')
  2. <iframe src="http://www.web2py.com"></iframe>

IMG

It can be used to embed images into HTML:

  1. >>> print IMG(_src='http://example.com/image.png', _alt='test')
  2. <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:

  1. >>> print A(IMG(_src=URL('static', 'logo.png'), _alt="My Logo"),
  2. ... _href=URL('default', 'index'))
  3. ...
  4. <a href="/myapp/default/index">
  5. <img src="/myapp/static/logo.png" alt="My Logo" />
  6. </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”.

  1. >>> print INPUT(_name='test', _value='a')
  2. <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:

  1. >>> print INPUT(_name='test', _value='a', value='b')
  2. <input value="b" name="test" />

For radio buttons, INPUT selectively sets the “checked” attribute:

  1. >>> for v in ['a', 'b', 'c']:
  2. ... print INPUT(_type='radio', _name='test', _value=v, value='b'), v
  3. ...
  4. <input value="a" type="radio" name="test" /> a
  5. <input value="b" type="radio" checked="checked" name="test" /> b
  6. <input value="c" type="radio" name="test" /> c

and similarly for checkboxes:

  1. >>> print INPUT(_type='checkbox', _name='test', _value='a', value=True)
  2. <input value="a" type="checkbox" checked="checked" name="test" />
  3. >>> print INPUT(_type='checkbox', _name='test', _value='a', value=False)
  4. <input value="a" type="checkbox" name="test" />

LABEL

It is used to create a LABEL tag for an INPUT field.

  1. >>> print LABEL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <label id="0" class="test">&lt;hello&gt;<b>world</b></label>

LEGEND

It is used to create a legend tag for a field in a form.

  1. >>> print LEGEND('Name', _for='myfield')
  2. <legend for="myfield">Name</legend>

LI

It makes a list item and should be contained in a UL or OL tag.

  1. >>> print LI('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <li id="0" class="test">&lt;hello&gt;<b>world</b></li>

META

To be used for building META tags in the HTML head. For example:

  1. >>> print META(_name='security', _content='high')
  2. <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:

  1. >>> print MARKMIN("this is **bold** or ''italic'' and this [[a link http://web2py.com]]")
  2. <p>this is <b>bold</b> or <i>italic</i> and
  3. 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:

  1. m = "Hello **world** [[link http://web2py.com]]"
  2. from gluon.contrib.markmin.markmin2html import markmin2html
  3. print markmin2html(m)
  4. from gluon.contrib.markmin.markmin2latex import markmin2latex
  5. print markmin2latex(m)
  6. from gluon.contrib.markmin.markmin2pdf import markmin2pdf
  7. print markmin2pdf(m) # requires pdflatex

(the MARKMIN helper is a shortcut for markmin2html)

Here is a basic syntax primer:

SOURCEOUTPUT
# titletitle
## sectionsection
### subsectionsubsection
boldbold
‘’italic’’italic
verbatimverbatim
http://google.comhttp://google.com
http://…<a href=”http://...">http:...</a&gt;
http://...png<img src=”http://...png“ />
http://...mp3<audio src=”http://...mp3"></audio&gt;
http://...mp4<video src=”http://...mp4"></video&gt;
qr:http://…<a href=”http://..."><img src=”qr code”/></a>
embed:http://…<iframe src=”http://..."></iframe&gt;
[[click me #myanchor]]click me
[[myanchor]]Creating an anchor for a link
$$\int_a^b sin(x)dx$$Built-in helpers - 图1
MARKMIN links

Links take this form:

  1. [[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

tags).

Adding a link with the qr: prefix such as

  1. 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

  1. 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:

  1. [[image-description http://.../image.png right 200px]]
MARKMIN lists and tables

Unordered lists with:

  1. - one
  2. - two
  3. - three

Ordered lists with:

  1. + one
  2. + two
  3. + three

and tables with:

  1. ----------
  2. X | 0 | 0
  3. 0 | X | 0
  4. 0 | 0 | 1
  5. ----------
extending MARKMIN

The MARKMIN syntax also supports blockquotes, HTML5 audio and video tags, image alignment, custom css, and it can be extended:

  1. MARKMIN("``abab``:custom", extra=dict(custom=lambda text: text.replace('a', 'c'))

generates

  1. '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.

  1. >>> print OBJECT('<hello>', XML('<b>world</b>'), _src='http://www.web2py.com')
  2. <object src="http://www.web2py.com">&lt;hello&gt;<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.

  1. >>> print OL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <ol id="0" class="test"><li>&lt;hello&gt;</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.

  1. >>> print INPUT(_type='checkbox', _name='test', _checked=ON)
  2. <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.

  1. >>> print SELECT('a', OPTGROUP('b', 'c'))
  2. <select>
  3. <option value="a">a</option>
  4. <optgroup>
  5. <option value="b">b</option>
  6. <option value="c">c</option>
  7. </optgroup>
  8. </select>

OPTION

This should only be used as part of a SELECT/OPTION combination.

  1. >>> print OPTION('<hello>', XML('<b>world</b>'), _value='a')
  2. <option value="a">&lt;hello&gt;<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”.

  1. >>> print SELECT('a', 'b', value='b'):
  2. <select>
  3. <option value="a">a</option>
  4. <option value="b" selected="selected">b</option>
  5. </select>

P

This is for tagging a paragraph.

  1. >>> print P('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <p id="0" class="test">&lt;hello&gt;<b>world</b></p>

PRE

Generates a <pre>...</pre> tag for displaying pre-formatted text. The CODE helper is generally preferable for code listings.

  1. >>> print PRE('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <pre id="0" class="test">&lt;hello&gt;<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.

  1. >>> print SCRIPT('alert("hello world");', _type='text/javascript')
  2. <script type="text/javascript"><!--
  3. alert("hello world");
  4. //--></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.

  1. >>> print SELECT('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <select id="0" class="test">
  3. <option value="&lt;hello&gt;">&lt;hello&gt;</option>
  4. <option value="&lt;b&gt;world&lt;/b&gt;"><b>world</b></option>
  5. </select>

SPAN

Similar to DIV but used to tag inline (rather than block) content.

  1. >>> print SPAN('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <span id="0" class="test">&lt;hello&gt;<b>world</b></span>

STYLE

Similar to script, but used to either include or link CSS code. Here the CSS is included:

  1. >>> print STYLE(XML('body {color: white}'))
  2. <style><!--
  3. body { color: white }
  4. //--></style>

and here it is linked:

  1. >>> print STYLE(_src='style.css')
  2. <style src="style.css"><!--
  3. //--></style>

TABLE, TR, TD

These tags (along with the optional THEAD, TBODY and TFOOTER helpers) are used to build HTML tables.

  1. >>> print TABLE(TR(TD('a'), TD('b')), TR(TD('c'), TD('d')))
  2. <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.

  1. >>> print TABLE(TR('a', 'b'), TR('c', 'd'))
  2. <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:

  1. >>> table = [['a', 'b'], ['c', 'd']]
  2. >>> print TABLE(TR(*table[0]), TR(*table[1]))
  3. <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:

  1. >>> table = [['a', 'b'], ['c', 'd']]
  2. >>> print TABLE(*[TR(*rows) for rows in table])
  3. <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.

  1. >>> print TBODY(TR('<hello>'), _class='test', _id=0)
  2. <tbody id="0" class="test"><tr><td>&lt;hello&gt;</td></tr></tbody>

TEXTAREA

This helper makes a <textarea>...</textarea> tag.

  1. >>> print TEXTAREA('<hello>', XML('<b>world</b>'), _class='test')
  2. <textarea class="test" cols="40" rows="10">&lt;hello&gt;<b>world</b></textarea>

The only caveat is that its optional “value” overrides its content (inner HTML)

  1. >>> print TEXTAREA(value="<hello world>", _class="test")
  2. <textarea class="test" cols="40" rows="10">&lt;hello world&gt;</textarea>

TFOOT

This is used to tag table footer rows.

  1. >>> print TFOOT(TR(TD('<hello>')), _class='test', _id=0)
  2. <tfoot id="0" class="test"><tr><td>&lt;hello&gt;</td></tr></tfoot>

TH

This is used instead of TD in table headers.

  1. >>> print TH('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <th id="0" class="test">&lt;hello&gt;<b>world</b></th>

THEAD

This is used to tag table header rows.

  1. >>> print THEAD(TR(TH('<hello>')), _class='test', _id=0)
  2. <thead id="0" class="test"><tr><th>&lt;hello&gt;</th></tr></thead>

TITLE

This is used to tag the title of a page in an HTML header.

  1. >>> print TITLE('<hello>', XML('<b>world</b>'))
  2. <title>&lt;hello&gt;<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.

  1. >>> print TR('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <tr id="0" class="test"><td>&lt;hello&gt;</td><td><b>world</b></td></tr>

TT

Tags text as typewriter (monospaced) text.

  1. >>> print TT('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <tt id="0" class="test">&lt;hello&gt;<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.

  1. >>> print UL('<hello>', XML('<b>world</b>'), _class='test', _id=0)
  2. <ul id="0" class="test"><li>&lt;hello&gt;</li><li><b>world</b></li></ul>

URL

The URL helper is documented in Chapter 4 URL

embed64

  1. 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

  1. xmlescape(data, quote=True)

returns an escaped string of the provided data.

  1. >>> print xmlescape('<hello>')
  2. &lt;hello&gt;