Helpers that produce simple HTML tags.

Most helpers have an **attrs argument to specify additional HTML attributes. A trailing underscore in the name will be deleted; this is especially important for attributes that are identical to Python keywords; e.g., class_. Some helpers handle certain keywords specially; these are noted in the helpers’ docstrings.

To create your own custom tags, see webhelpers.html.builder.

A set of CSS styles complementing these helpers is in webhelpers/public/stylesheets/webhelpers.css.

Form tags

webhelpers.html.tags.form(url, method='post', multipart=False, hidden_fields=None, **attrs)

An open tag for a form that will submit to url.

You must close the form yourself by calling end_form() or outputting </form>.


The method to use when submitting the form, usually either “GET” or “POST”. If “PUT”, “DELETE”, or another verb is used, a hidden input with name _method is added to simulate the verb over POST.
If set to True, the enctype is set to “multipart/form-data”. You must set it to true when uploading files, or the browser will submit the filename rather than the file.
Additional hidden fields to add to the beginning of the form. It may be a dict or an iterable of key-value tuples. This is implemented by calling the object’s .items() method if it has one, or just iterating the object. (This will successfuly get multiple values for the same key in WebOb MultiDict objects.)

Because input tags must be placed in a block tag rather than directly inside the form, all hidden fields will be put in a ‘<div style=”display:none”>’. The style prevents the <div> from being displayed or affecting the layout.


>>> form("/submit")
literal(u'<form action="/submit" method="post">')
>>> form("/submit", method="get")
literal(u'<form action="/submit" method="get">')
>>> form("/submit", method="put")
literal(u'<form action="/submit" method="post"><div style="display:none">\n<input name="_method" type="hidden" value="put" />\n</div>\n')
>>> form("/submit", "post", multipart=True) 
literal(u'<form action="/submit" enctype="multipart/form-data" method="post">')

Changed in WebHelpers 1.0b2: add <div> and hidden_fields arg.

Changed in WebHelpers 1.2: don’t add an “id” attribute to hidden tags generated by this helper; they clash if there are multiple forms on the page.


Output “</form>”.


>>> end_form()
webhelpers.html.tags.text(name, value=None, id=<class 'webhelpers.misc.NotGiven'>, type='text', **attrs)

Create a standard text field.

value is a string, the content of the text field.

id is the HTML ID attribute, and should be passed as a keyword argument. By default the ID is the same as the name filtered through _make_safe_id_component(). Pass None to suppress the ID attribute entirely.

type is the input field type, normally “text”. You can override it for HTML 5 input fields that don’t have their own helper; e.g., “search”, “email”, “date”.


  • disabled - If set to True, the user will not be able to use

    this input.

  • size - The number of visible characters that will fit in the


  • maxlength - The maximum number of characters that the browser

    will allow the user to enter.

The remaining keyword args will be standard HTML attributes for the tag.

Example, a text input field:

>>> text("address")
literal(u'<input id="address" name="address" type="text" />')

HTML 5 example, a color picker:

>>> text("color", type="color")
literal(u'<input id="color" name="color" type="color" />')
webhelpers.html.tags.textarea(name, content='', id=<class 'webhelpers.misc.NotGiven'>, **attrs)

Create a text input area.


>>> textarea("body", "", cols=25, rows=10)
literal(u'<textarea cols="25" id="body" name="body" rows="10"></textarea>')
webhelpers.html.tags.hidden(name, value=None, id=<class 'webhelpers.misc.NotGiven'>, **attrs)

Create a hidden field.

webhelpers.html.tags.file(name, value=None, id=<class 'webhelpers.misc.NotGiven'>, **attrs)

Create a file upload field.

If you are using file uploads then you will also need to set the multipart option for the form.


>>> file('myfile')
literal(u'<input id="myfile" name="myfile" type="file" />')
webhelpers.html.tags.password(name, value=None, id=<class 'webhelpers.misc.NotGiven'>, **attrs)

Create a password field.

Takes the same options as text().

webhelpers.html.tags.checkbox(name, value='1', checked=False, label=None, id=<class 'webhelpers.misc.NotGiven'>, **attrs)

Create a check box.

Arguments: name – the widget’s name.

value – the value to return to the application if the box is checked.

checked – true if the box should be initially checked.

label – a text label to display to the right of the box.

id is the HTML ID attribute, and should be passed as a keyword argument. By default the ID is the same as the name filtered through _make_safe_id_component(). Pass None to suppress the ID attribute entirely.

The following HTML attributes may be set by keyword argument:

  • disabled - If true, checkbox will be grayed out.
  • readonly - If true, the user will not be able to modify the checkbox.

To arrange multiple checkboxes in a group, see webhelpers.containers.distribute().


>>> checkbox("hi")
literal(u'<input id="hi" name="hi" type="checkbox" value="1" />')
webhelpers.html.tags.radio(name, value, checked=False, label=None, **attrs)

Create a radio button.

Arguments: name – the field’s name.

value – the value returned to the application if the button is pressed.

checked – true if the button should be initially pressed.

label – a text label to display to the right of the button.

The id of the radio button will be set to the name + ‘_’ + value to ensure its uniqueness. An id keyword arg overrides this. (Note that this behavior is unique to the radio() helper.)

To arrange multiple radio buttons in a group, see webhelpers.containers.distribute().

webhelpers.html.tags.submit(name, value, id=<class 'webhelpers.misc.NotGiven'>, **attrs)

Create a submit button with the text value as the caption.

webhelpers.html.tags.select(name, selected_values, options, id=<class 'webhelpers.misc.NotGiven'>, **attrs)

Create a dropdown selection box.

  • name – the name of this control.
  • selected_values – a string or list of strings or integers giving the value(s) that should be preselected.
  • options – an Options object or iterable of (value, label) pairs. The label will be shown on the form; the option will be returned to the application if that option is chosen. If you pass a string or int instead of a 2-tuple, it will be used for both the value and the label. If the value is a tuple or a list, it will be added as an optgroup, with label as label.

id is the HTML ID attribute, and should be passed as a keyword argument. By default the ID is the same as the name. filtered through _make_safe_id_component(). Pass None to suppress the ID attribute entirely.

CAUTION: the old rails helper options_for_select had the label first. The order was reversed because most real-life collections have the value first, including dicts of the form {value: label}. For those dicts you can simply pass D.items() as this argument.

HINT: You can sort options alphabetically by label via: sorted(my_options, key=lambda x: x[1])

The following options may only be keyword arguments:

  • multiple – if true, this control will allow multiple


  • prompt – if specified, an extra option will be prepended to the list: (“”, prompt). This is intended for those “Please choose ...” pseudo-options. Its value is “”, equivalent to not making a selection.

Any other keyword args will become HTML attributes for the <select>.

Examples (call, result):

>>> select("currency", "$", [["$", "Dollar"], ["DKK", "Kroner"]])
literal(u'<select id="currency" name="currency">\n<option selected="selected" value="$">Dollar</option>\n<option value="DKK">Kroner</option>\n</select>')
>>> select("cc", "MasterCard", [ "VISA", "MasterCard" ], id="cc", class_="blue")
literal(u'<select class="blue" id="cc" name="cc">\n<option value="VISA">VISA</option>\n<option selected="selected" value="MasterCard">MasterCard</option>\n</select>')
>>> select("cc", ["VISA", "Discover"], [ "VISA", "MasterCard", "Discover" ])
literal(u'<select id="cc" name="cc">\n<option selected="selected" value="VISA">VISA</option>\n<option value="MasterCard">MasterCard</option>\n<option selected="selected" value="Discover">Discover</option>\n</select>')
>>> select("currency", None, [["$", "Dollar"], ["DKK", "Kroner"]], prompt="Please choose ...")
literal(u'<select id="currency" name="currency">\n<option selected="selected" value="">Please choose ...</option>\n<option value="$">Dollar</option>\n<option value="DKK">Kroner</option>\n</select>')
>>> select("privacy", 3L, [(1, "Private"), (2, "Semi-public"), (3, "Public")])
literal(u'<select id="privacy" name="privacy">\n<option value="1">Private</option>\n<option value="2">Semi-public</option>\n<option selected="selected" value="3">Public</option>\n</select>')
>>> select("recipients", None, [([("u1", "User1"), ("u2", "User2")], "Users"), ([("g1", "Group1"), ("g2", "Group2")], "Groups")])
literal(u'<select id="recipients" name="recipients">\n<optgroup label="Users">\n<option value="u1">User1</option>\n<option value="u2">User2</option>\n</optgroup>\n<optgroup label="Groups">\n<option value="g1">Group1</option>\n<option value="g2">Group2</option>\n</optgroup>\n</select>')
class webhelpers.html.tags.Options

A tuple of Option objects for the select() helper.

select() calls this automatically so you don’t have to. However, you may find it useful for organizing your code, and its methods can be convenient.

This class has multiple jobs:

  • Canonicalize the options given to select() into a consistent format.
  • Avoid canonicalizing the same data multiple times. It subclasses tuple rather than a list to guarantee that nonconformant elements won’t be added after canonicalization.
  • Provide convenience methods to iterate the values and labels separately.
>>> opts = Options(["A", 1, ("b", "B")])
>>> opts
Options([(u'A', u'A'), (u'1', u'1'), (u'b', u'B')])
>>> list(opts.values())
[u'A', u'1', u'b']
>>> list(opts.labels())
[u'A', u'1', u'B']
>>> opts[2].value
>>> opts[2].label

Iterate the label element of each pair.


Iterate the value element of each pair.

class webhelpers.html.tags.Option(value, label)

An option for an HTML select.

A simple container with two attributes, .value and .label.

class webhelpers.html.tags.OptGroup(label, options)

A container for Options

webhelpers.html.tags.title(title, required=False, label_for=None)

Format the user-visible title for a form field.

Use this for forms that have a text title above or next to each field.

title – the name of the field; e.g., “First Name”.

required – if true, append a *” to the title and use the ‘required’ HTML format (see example); otherwise use the ‘not required’ format.

label_for – if provided, put <label for="ID"> around the title. The value should be the HTML ID of the input field related to this title. Per the HTML standard, the ID should point to a single control (input, select, textarea), not to multiple controls (fieldset, group of checkboxes, group of radio buttons). ID’s are set by passing the keyword arg id to the appropriate helper.

Note that checkboxes and radio buttions typically have their own individual labels in addition to the title. You can set these with the label argument to checkbox() and radio().

This helper does not accept other keyword arguments.

See webhepers/public/stylesheets/webhelpers.css for suggested styles.

>>> title("First Name")
literal(u'<span class="not-required">First Name</span>')
>>> title("Last Name", True)
literal(u'<span class="required">Last Name <span class="required-symbol">*</span></span>')
>>> title("First Name", False, "fname")
literal(u'<span class="not-required"><label for="fname">First Name</label></span>')
>>> title("Last Name", True, label_for="lname")
literal(u'<span class="required"><label for="lname">Last Name</label> <span class="required-symbol">*</span></span>')

Return an inline HTML snippet explaining which fields are required.

See webhepers/public/stylesheets/webhelpers.css for suggested styles.

>>> required_legend()
literal(u'<span class="required required-symbol">*</span> = required')

ModelTags class

class webhelpers.html.tags.ModelTags(record, use_keys=False, date_format='%m/%d/%Y', id_format=None)

A nice way to build a form for a database record.

ModelTags allows you to build a create/update form easily. (This is the C and U in CRUD.) The constructor takes a database record, which can be a SQLAlchemy mapped class, or any object with attributes or keys for the field values. Its methods shadow the the form field helpers, but it automatically fills in the value attribute based on the current value in the record. (It also knows about the ‘checked’ and ‘selected’ attributes for certain tags.)

You can also use the same form to input a new record. Pass None or "" instead of a record, and it will set all the current values to a default value, which is either the default keyword arg to the method, or “” if not specified.

(Hint: in Pylons you can put mt = ModelTags(c.record) in your template, and then if the record doesn’t exist you can either set c.record = None or not set it at all. That’s because nonexistent c attributes resolve to “” unless you’ve set config["pylons.strict_c"] = True. However, having a c attribute that’s sometimes set and sometimes not is arguably bad programming style.)

checkbox(name, value='1', label=None, **kw)

Build a checkbox field.

The box will be initially checked if the value of the corresponding database field is true.

The submitted form value will be “1” if the box was checked. If the box is unchecked, no value will be submitted. (This is a downside of the standard checkbox tag.)

To display multiple checkboxes in a group, see webhelper.containers.distribute().

date(name, **kw)

Same as text but format a date value into a date string.

The value can be a datetime.date, datetime.datetime, None, or “”. The former two are converted to a string using the date format passed to the constructor. The latter two are converted to “”.

If there’s no database record, consult keyword arg default. It it’s the string “today”, use todays’s date. Otherwise it can be any of the values allowed above. If no default is specified, the text field is initialized to “”.

Hint: you may wish to attach a Javascript calendar to the field.

file(name, **kw)

Build a file upload field.

User agents may or may not respect the contents of the ‘value’ attribute.

hidden(name, **kw)

Build a hidden HTML field.

password(name, **kw)

Build a password field.

This is the same as a text box but the value will not be shown on the screen as the user types.

radio(name, checked_value, label=None, **kw)

Build a radio button.

The radio button will initially be selected if the database value equals checked_value. On form submission the value will be checked_value if the button was selected, or "" otherwise.

In case of a ModelTags object that is created from scratch (e.g. new_employee=ModelTags(None)) the option that should be checked can be set by the ‘default’ parameter. As in: new_employee.radio('status', checked_value=7, default=7)

The control’s ‘id’ attribute will be modified as follows:

  1. If not specified but an ‘id_format’ was given to the constructor, generate an ID based on the format.
  2. If an ID was passed in or was generated by step (1), append an underscore and the checked value. Before appending the checked value, lowercase it, change any spaces to "_", and remove any non-alphanumeric characters except underscores and hyphens.
  3. If no ID was passed or generated by step (1), the radio button will not have an ‘id’ attribute.

To display multiple radio buttons in a group, see webhelper.containers.distribute().

select(name, options, **kw)

Build a dropdown select box or list box.

See the select() function for the meaning of the arguments.

If the corresponding database value is not a list or tuple, it’s wrapped in a one-element list. But if it’s “” or None, an empty list is substituted. This is to accommodate multiselect lists, which may have multiple values selected.

text(name, **kw)

Build a text box.

textarea(name, **kw)

Build a rectangular text area.

Table tags

webhelpers.html.tags.th_sortable(current_order, column_order, label, url, class_if_sort_column='sort', class_if_not_sort_column=None, link_attrs=None, name='th', **attrs)

<th> for a “click-to-sort-by” column.

Convenience function for a sortable column. If this is the current sort column, just display the label and set the cell’s class to class_if_sort_column.

current_order is the table’s current sort order. column_order is the value pertaining to this column. In other words, if the two are equal, the table is currently sorted by this column.

If this is the sort column, display the label and set the <th>’s class to class_if_sort_column.

If this is not the sort column, display an <a> hyperlink based on label, url, and link_attrs (a dict), and set the <th>’s class to class_if_not_sort_column.

url is the literal href= value for the link. Pylons users would typically pass something like url=h.url_for("mypage", sort="date").

**attrs are additional attributes for the <th> tag.

If you prefer a <td> tag instead of <th>, pass name="td".

To change the sort order via client-side Javascript, pass url=None and the appropriate Javascript attributes in link_attrs.


>>> sort = "name"
>>> th_sortable(sort, "name", "Name", "?sort=name")
literal(u'<th class="sort">Name</th>')
>>> th_sortable(sort, "date", "Date", "?sort=date")
literal(u'<th><a href="?sort=date">Date</a></th>')
>>> th_sortable(sort, "date", "Date", None, link_attrs={"onclick": "myfunc()"})
literal(u'<th><a onclick="myfunc()">Date</a></th>')

Other non-form tags

webhelpers.html.tags.ol(items, default=literal(u''), li_attrs=None, **attrs)

Return an ordered list with each item wrapped in <li>.

list of strings.
value returned _instead of the <ol>_ if there are no items in the list. If None, return an empty <ol>.
dict of attributes for the <li> tags.


>>> ol(["foo", "bar"])
>>> ol(["A", "B"], li_attrs={"class_": "myli"}, class_="mylist") 
literal(u'<ol class="mylist">\n<li class="myli">A</li>\n<li class="myli">B</li>\n</ol>')
>>> ol([])
webhelpers.html.tags.ul(items, default=None, li_attrs=None, **attrs)

Return an unordered list with each item wrapped in <li>.

list of strings.
value returned _instead of the <ul>_ if there are no items in the list. If None, return an empty <ul>.
dict of attributes for the <li> tags.


>>> ul(["foo", "bar"])
>>> ul(["A", "B"], li_attrs={"class_": "myli"}, class_="mylist") 
literal(u'<ul class="mylist">\n<li class="myli">A</li>\n<li class="myli">B</li>\n</ul>')
>>> ul([])
>>> ul([], default="")
>>> ul([], default=literal('<span class="no-data">No data</span>'))
literal(u'<span class="no-data">No data</span>')
>>> ul(["A"], default="NOTHING")
webhelpers.html.tags.image(url, alt, width=None, height=None, path=None, use_pil=False, **attrs)

Return an image tag for the specified source.

The URL of the image. (This must be the exact URL desired. A previous version of this helper added magic prefixes; this is no longer the case.)
The img’s alt tag. Non-graphical browsers and screen readers will output this instead of the image. If the image is pure decoration and uninteresting to non-graphical users, pass “”. To omit the alt tag completely, pass None.
The width of the image, default is not included.
The height of the image, default is not included.
Calculate the width and height based on the image file at path if possible. May not be specified if width or height is specified. The results are also written to the debug log for troubleshooting.
If true, calcuate the image dimensions using the Python Imaging Library, which must be installed. Otherwise use a pure Python algorithm which understands fewer image formats and may be less accurate. This flag controls whether webhelpers.media.get_dimensions_pil or webhelpers.media.get_dimensions is called. It has no effect if path is not specified.


>>> image('/images/rss.png', 'rss syndication')
literal(u'<img alt="rss syndication" src="/images/rss.png" />')

>>> image('/images/xml.png', "")
literal(u'<img alt="" src="/images/xml.png" />')

>>> image("/images/icon.png", height=16, width=10, alt="Edit Entry")
literal(u'<img alt="Edit Entry" height="16" src="/images/icon.png" width="10" />')

>>> image("/icons/icon.gif", alt="Icon", width=16, height=16)
literal(u'<img alt="Icon" height="16" src="/icons/icon.gif" width="16" />')

>>> image("/icons/icon.gif", None, width=16)
literal(u'<img alt="" src="/icons/icon.gif" width="16" />')

A break tag (“<br />”) followed by a newline. This is a literal constant, not a function.

Head tags and document type

Return CSS link tags for the specified stylesheet URLs.

urls should be the exact URLs desired. A previous version of this helper added magic prefixes; this is no longer the case.


>>> stylesheet_link('/stylesheets/style.css')
literal(u'<link href="/stylesheets/style.css" media="screen" rel="stylesheet" type="text/css" />')

>>> stylesheet_link('/stylesheets/dir/file.css', media='all')
literal(u'<link href="/stylesheets/dir/file.css" media="all" rel="stylesheet" type="text/css" />')

Return script include tags for the specified javascript URLs.

urls should be the exact URLs desired. A previous version of this helper added magic prefixes; this is no longer the case.

Specify the keyword argument defer=True to enable the script defer attribute.


>>> print javascript_link('/javascripts/prototype.js', '/other-javascripts/util.js')
<script src="/javascripts/prototype.js" type="text/javascript"></script>
<script src="/other-javascripts/util.js" type="text/javascript"></script>

>>> print javascript_link('/app.js', '/test/test.1.js')
<script src="/app.js" type="text/javascript"></script>
<script src="/test/test.1.js" type="text/javascript"></script>

Return a link tag allowing auto-detecting of RSS or ATOM feed.

The auto-detection of feed for the current page is only for browsers and news readers that support it.

The URL of the feed. (This should be the exact URLs desired. A previous version of this helper added magic prefixes; this is no longer the case.)
The type of feed. Specifying ‘rss’ or ‘atom’ automatically translates to a type of ‘application/rss+xml’ or ‘application/atom+xml’, respectively. Otherwise the type is used as specified. Defaults to ‘rss’.


>>> auto_discovery_link('http://feed.com/feed.xml')
literal(u'<link href="http://feed.com/feed.xml" rel="alternate" title="RSS" type="application/rss+xml" />')

>>> auto_discovery_link('http://feed.com/feed.xml', feed_type='atom')
literal(u'<link href="http://feed.com/feed.xml" rel="alternate" title="ATOM" type="application/atom+xml" />')

>>> auto_discovery_link('app.rss', feed_type='atom', title='atom feed')
literal(u'<link href="app.rss" rel="alternate" title="atom feed" type="application/atom+xml" />')

>>> auto_discovery_link('/app.html', feed_type='text/html')
literal(u'<link href="/app.html" rel="alternate" title="" type="text/html" />')
class webhelpers.html.tags.Doctype

Document type declarations for HTML and XHTML.

html4(subtype='transitional', version='4.01')

Create a <!DOCTYPE> for HTML 4.


>>> Doctype().html4()
literal(u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">')
>>> Doctype().html4("strict")
literal(u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd">')
>>> Doctype().html4("frameset")
literal(u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">')

Create a <!DOCTYPE> for HTML 5.


>>> Doctype().html5()
literal(u'<!doctype html>')
xhtml1(subtype='transitional', version='1.0')

Create a <!DOCTYPE> for XHTML 1.


>>> Doctype().xhtml1()
literal(u'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">')
>>> Doctype().xhtml1("strict")
literal(u'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">')
>>> Doctype().xhtml1("frameset")
literal(u'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">')
webhelpers.html.tags.xml_declaration(version='1.0', encoding='utf-8')

Create an XML declaration.


>>> xml_declaration()
literal(u'<?xml version="1.0" encoding="utf-8" ?>')

Utility functions


Add CSS classes to a tag programmatically.

This helper is meant to be used as the class_ argument to a tag helper.

The argument is an iterable of (class, condition) pairs, where each class is a string and condition is a boolean. The function returns a space-separated list of classes whose conditions were true.

If all conditions are false, return None. This tells the caller to suppress the “class” attribute entirely.


>>> arg = [("first", False), ("even", True)]
>>> HTML.td("My content.", class_=css_classes(arg))
literal(u'<td class="even">My content.</td>')
>>> arg = [("first", True), ("even", True)]
>>> HTML.td("My content.", class_=css_classes(arg))
literal(u'<td class="first even">My content.</td>')
>>> arg = [("first", False), ("even", False)]
>>> HTML.td("My content.", class_=css_classes(arg))
literal(u'<td>My content.</td>')
webhelpers.html.tags.convert_boolean_attrs(attrs, bool_attrs)

Convert boolean values into proper HTML attributes.

attrs is a dict of HTML attributes, which will be modified in place.

bool_attrs is a list of attribute names.

For every element in bool_attrs, I look for a corresponding key in attrs. If its value is true, I change the value to match the key. For example, I convert selected=True into selected="selected". If the value is false, I delete the key.

Table Of Contents

Previous topic


Next topic