webhelpers2.html.tags

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 webhelpers2.html.builder.

Form tags

webhelpers2.html.tags.form(url, method=u'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>.

Options:

method
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.
multipart
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.
hidden_fields
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.

webhelpers2.html.tags.end_form()

Output "</form>".

webhelpers2.html.tags.text(name, value=None, id=<class 'webhelpers2.misc.NotGiven'>, type=u'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".

Options:

  • 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

    input.

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

webhelpers2.html.tags.textarea(name, content=u'', id=<class 'webhelpers2.misc.NotGiven'>, **attrs)

Create a text input area.

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

Create a hidden field.

webhelpers2.html.tags.file(name, value=None, id=<class 'webhelpers2.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.

Example:

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

Create a password field.

Takes the same options as text().

webhelpers2.html.tags.checkbox(name, value=u'1', checked=False, label=None, label_class=None, id=<class 'webhelpers2.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. This puts a <label> tag around the input tag.

label_class -- CSS class for <label> tag. This should be a keyword argument because its position may change in a future version.

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 webhelpers2.containers.distribute().

webhelpers2.html.tags.radio(name, value, checked=False, label=None, label_class=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. This puts a <label> tag around the input tag.

label_class -- CSS class for <label> tag. This should be a keyword argument because its position may change in a future version.

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 webhelpers2.containers.distribute().

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

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

Select and Options helpers

The select helper creates a dropdown selection box. It's mostly a wrapper around the Options class, which in turn is a container of Option and/or OptGroup instances.

You can call Options.render on its own to create a set of options. This can be useful to manually place options inside an HTML <select> in a template, or in an HTML 5 <datalist>.

There are four main differences compared to WebHelpers:

  1. The availability of Options.render.
  2. API overhaul in Options, Option, and OptGroup, including "label before value" argument order.
  3. If an option has no 'value' argument or it's identical to the label, then the Option.value attribute will be None, the HTML <option> tag will have no 'value' attribute, and on form submission the parameter will be the same as the label. We originally believed the 'value' attribute was required in HTML, but it's optional in HTML 5 and 4.0.1. This is distinct from a value of "" (the empty string), which renders as is and on form submission the parameter will be empty or missing.
  4. [Late change in 2.0rc3] The options argument to select no longer accepts lists of lists, lists of tuples, or other complex data structures. You can no longer pass [(myvalue, mylabel)] or [(optgroup_label, options)]; these now raise TypeError. Instead you should explicitly build up an Options instance and pass it. This restriction was made for simplicity, reliability, and maintainability.
webhelpers2.html.tags.select(name, selected_values, options, id=<class 'webhelpers2.misc.NotGiven'>, **attrs)

Create a dropdown selection box.

Arguments:

  • name: the name of this control.
  • selected_values: the value(s) that should be preselected. A string or list of strings. Some other types are allowed; see the Options.render method for details.
  • options: an Options instance, or an iterable to pass to the its constructor. See the Options class for allowed element types.
  • id: the HTML ID attribute. This should be a keyword argument if passed. 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 options may only be keyword arguments:

  • multiple: if true, this control will allow multiple selections.
  • prompt: An extra option that will be prepended to the list. The argument is the option label; e.g., "Please choose ...". The generated option's value will be the empty string (""), which is equivalent to not making a selection. If you specify this and also pass an Options instance in options, it will combine the two into a new Options object rather than reusing the existing one.

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

class webhelpers2.html.tags.Options(options=None, prompt=None)

A list of options and/or optgroups for a select or datalist.

I'm a subclass of list. My elements are Option and/or OptGroup instances. Do not add other element types or they may cause options.render or str(options) to fail.

__init__(options=None, prompt=None)

Construct an Options instance.

options: An iterable of Option instances, OptGroup instances and/or strings. If you pass strings, they will be converted to simple Option instances (i.e., the label will be the string, and the value will be None).

prompt: If passed, this will be turned into an extra option before the others. The string argument will become the option's label, and the option's value will be the empty string.

add_optgroup(label, options=None)

Create an OptGroup, append it, and return it.

The return value is the OptGroup instance. Call its .add_option method to add options to the group.

add_option(label, value=None)

Create an option and append it to the list.

  • label: the option's text label. String.
  • value: the option's value if selected. Optional.
render(selected_values=None)

Render the options as a concatenated literal of <option> and/or <optgroup> tags, with a newline after each.

selected_values: The value(s) that should be preselected. You can pass a string, int, bool, or other scalar type, or a sequence of these. If you pass a scalar it will be standardized to a one-element tuple. If you don't pass anything, it will default to ("",) (a tuple containing the empty string); this will correctly preselect prompts.

Note that selected_values does not do type conversions. If you pass an int, the corresponding Option.value must also be an int or otherwise equal to it. (The actual comparision operator is in.)

Calling str(options) or options.__html__() is the same as calling options.render() without arguments. This is only useful if you don't want to pass any selected values.

class webhelpers2.html.tags.Option(label, value=None)

An option for a select or datalist.

I can be an element in Options.

__init__(label, value=None)

Construct an Option.

class webhelpers2.html.tags.OptGroup(label, options=None)

A group of options.

I'm a subclass of list. My elements are Option instances. I can be an element in Options.

__init__(label, options=None)

Construct an OptGroup.

label: The group's label.

options: An iterable of Option instances, and/or strings. If you pass strings, they will be converted to simple Option instances (i.e., the label will be the string, and the value will be None).

add_option(label, value=None)

Create an option and append it to the list.

  • label: the option's text label. String.
  • value: the option's value if selected. Optional.

ModelTags class

class webhelpers2.html.tags.ModelTags(record, use_keys=False, date_format=u'%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.

__init__(record, use_keys=False, date_format=u'%m/%d/%Y', id_format=None)

Create a ModelTags object.

record is the database record to lookup values in. It may be any object with attributes or keys, including a SQLAlchemy mapped instance. It may also be None or "" to indicate that a new record is being created. (The class attribute undefined_values tells which values indicate a new record.)

If use_keys is true, values will be looked up by key. If false (default), values will be looked up by attribute.

date_format is a strftime-compatible string used by the .date method. The default is American format (MM/DD/YYYY), which is most often seen in text fields paired with popup calendars. European format (DD/MM/YYYY) is "%d/%m/%Y". ISO format (YYYY-MM-DD) is "%Y-%m-%d".

id_format is a formatting-operator format for the HTML 'id' attribute. It should contain one "{}" where the tag's name will be embedded. For backward compatibility with WebHelpers, "%s" is automatically converted to "{}".

checkbox(name, value=u'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

webhelpers2.html.tags.th_sortable(current_order, column_order, label, url, class_if_sort_column=u'sort', class_if_not_sort_column=None, link_attrs=None, name=u'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.

Other non-form tags

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

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

items
list of strings.
default
value returned _instead of the <ol>_ if there are no items in the list. If None, return an empty <ol>.
li_attrs
dict of attributes for the <li> tags.
webhelpers2.html.tags.ul(items, default=None, li_attrs=None, **attrs)

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

items
list of strings.
default
value returned _instead of the <ul>_ if there are no items in the list. If None, return an empty <ul>.
li_attrs
dict of attributes for the <li> tags.
webhelpers2.html.tags.image(url, alt, width=None, height=None, **attrs)

Return an image tag for the specified source.

url
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.)
alt
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.
width
The width of the image, default is not included.
height
The height of the image, default is not included.

Note: This version does not support the 'path' and 'use_pil' arguments, because they depended on the WebHelpers 'media' subpackage which was dropped in WebHelpers 2.

webhelpers2.html.tags.BR

Same as HTML.BR. 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.

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.

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.

url
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.)
feed_type
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'.

Utilities

webhelpers2.html.tags._make_safe_id_component(idstring)

Make a string safe for including in an id attribute.

The HTML spec says that id attributes 'must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".")'. These regexps are slightly over-zealous, in that they remove colons and periods unnecessarily.

Whitespace is transformed into underscores, and then anything which is not a hyphen or a character that matches w (alphanumerics and underscore) is removed.