webhelpers.html – HTML handling

webhelpers.html.builder

HTML/XHTML tag builder

HTML Builder provides an HTML object that creates (X)HTML tags in a Pythonic way, a literal class used to mark strings containing intentional HTML markup, and a smart escape() function that preserves literals but escapes other strings that may accidentally contain markup characters (“<”, “>”, “&”) or malicious Javascript tags. Escaped strings are returned as literals to prevent them from being double-escaped later.

literal is a subclass of unicode, so it works with all string methods and expressions. The only thing special about it is the .__html__ method, which returns the string itself. escape() follows a simple protocol: if the object has an .__html__ method, it calls that rather than .__str__ to get the HTML representation. Third-party libraries that do not want to import literal (and this create a dependency on WebHelpers) can put an .__html__ method in their own classes returning the desired HTML representation.

When used in a mixed expression containing both literals and ordinary strings, literal tries hard to escape the strings and return a literal. However, this depends on which value has “control” of the expression. literal seems to be able to take control with all combinations of the + operator, but with % and join it must be on the left side of the expression. So these all work:

"A" + literal("B")
literal(", ").join(["A", literal("B")])
literal("%s %s") % (16, literal("kg"))

But these return an ordinary string which is prone to double-escaping later:

"\\n".join([literal('<span class="foo">Foo!</span>'), literal('Bar!')])
"%s %s" % (literal("16"), literal("&lt;em&gt;kg&lt;/em&gt;"))

Third-party libraries that don’t want to import literal and thus avoid a dependency on WebHelpers can add an .__html__ method to any class, which can return the same as .__str__ or something else. escape() trusts the HTML method and does not escape the return value. So only strings that lack an .__html__ method will be escaped.

The HTML object has the following methods for tag building:

HTML(*strings)

Escape the string args, concatenate them, and return a literal. This is the same as escape(s) but accepts multiple strings. Multiple args are useful when mixing child tags with text, such as:

html = HTML("The king is a >>", HTML.strong("fink"), "<<!")
HTML.literal(*strings)
Same as literal but concatenates multiple arguments.
HTML.comment(*strings)
Escape and concatenate the strings, and wrap the result in an HTML comment.
HTML.tag(tag, *content, **attrs)

Create an HTML tag tag with the keyword args converted to attributes. The other positional args become the content for the tag, and are escaped and concatenated. If an attribute name conflicts with a Python keyword (notably “class”), append an underscore. If an attribute value is None, the attribute is not inserted. Two special keyword args are recognized:

c
Specifies the content. This cannot be combined with content in positional args. The purpose of this argument is to position the content at the end of the argument list to match the native HTML syntax more closely. Its use is entirely optional. The value can be a string, a tuple, or a tag.
_close
If present and false, do not close the tag. Otherwise the tag will be closed with a closing tag or an XHTML-style trailing slash as described below.

Example:

>>> HTML.tag("a", href="http://www.yahoo.com", name=None,
... c="Click Here")
literal(u'<a href="http://www.yahoo.com">Click Here</a>')
HTML.__getattr__

Same as HTML.tag but using attribute access. Example:

>>> HTML.a("Foo", href="http://example.com/", class_="important")
literal(u'<a class="important" href="http://example.com/">Foo</a>')

The protocol is simple: if an object has an .__html__ method, escape() calls it rather than .__str__() to obtain a string representation.

About XHTML and HTML

This builder always produces tags that are valid as both HTML and XHTML. “Empty” tags (like <br>, <input> etc) are written like <br />, with a space and a trailing /.

Only empty tags get this treatment. The library will never, for example, product <script src="..." />, which is invalid HTML.

The W3C HTML validator validates these constructs as valid HTML Strict. It does produce warnings, but those warnings warn about the ambiguity if this same XML-style self-closing tags are used for HTML elements that can take content (<script>, <textarea>, etc). This library never produces markup like that.

Rather than add options to generate different kinds of behavior, we felt it was better to create markup that could be used in different contexts without any real problems and without the overhead of passing options around or maintaining different contexts, where you’d have to keep track of whether markup is being rendered in an HTML or XHTML context.

If you _really_ want tags without training slashes (e.g., <br>`)`, you can "abuse" ``_close=False to produce them.

class webhelpers.html.builder.UnfinishedTag(tag)
Represents an unfinished or empty tag.
class webhelpers.html.builder.UnfinishedComment
Represents an unfinished or empty comment.
class webhelpers.html.builder.UnfinishedLiteral
Represent an unfinished literal value.
class webhelpers.html.builder.HTMLBuilder
Base HTML object.
webhelpers.html.builder.make_tag(tag, *args, **kw)
webhelpers.html.builder.literal()

Represents an HTML literal.

This subclass of unicode has a .__html__() method that is detected by the escape() function.

Also, if you add another string to this string, the other string will be quoted and you will get back another literal object. Also literal(...) % obj will quote any value(s) from obj. If you do something like literal(...) + literal(...), neither string will be changed because escape(literal(...)) doesn’t change the original literal.

webhelpers.html.builder.lit_sub(*args, **kw)
Literal-safe version of re.sub. If the string to be operated on is a literal, return a literal result.
webhelpers.html.builder.escape(val, force=False)

Does HTML-escaping of a value.

Objects with a .__html__() method will have that method called, and the return value will not be quoted. Thus objects with that magic method can be used to represent HTML that should not be quoted.

As a special case, escape(None) returns ‘’

If force is true, then it will always be quoted regardless of __html__().

class webhelpers.html.builder._EscapedItem(obj, encoding, error_mode)

Wrapper/helper for literal(...) % obj

This quotes the object during string substitution, and if the object is dictionary(-like) it will quote all the values in the dictionary.

webhelpers.html.converters

webhelpers.html.converters.markdown(text, **kwargs)

Format the text to HTML with MarkDown formatting.

This function uses the Python MarkDown library which is included with WebHelpers. It does not include extensions due to circular import issues. If you need the footnotes or RSS extensions, use the full Markdown package instead.

IMPORTANT: If your source text is untrusted and may contain malicious HTML markup, pass safe_mode="escape" to escape it, safe_mode="replace" to replace it with a scolding message, or safe_mode="remove" to strip it.

There is at least one other Markdown package for Python. python-markdown2 (http://code.google.com/p/python-markdown2/), which claims to be faster and to handle edge cases better. WebHelpers is sticking to the original Python Markdown for now for backward compatibility and because nobody has complained about the speed.

webhelpers.html.converters.textilize(text, sanitize=False)

Format the text to HTML with Textile formatting.

This function uses the PyTextile library which is included with WebHelpers.

Additionally, the output can be sanitized which will fix tags like <img />, <br /> and <hr /> for proper XHTML output.

webhelpers.html.secure_form

webhelpers.html.secure_form.authentication_token()
Return the current authentication token, creating one if one doesn’t already exist.
webhelpers.html.secure_form.auth_token_hidden_field()
webhelpers.html.secure_form.secure_form(url, method='POST', multipart=False, **attrs)

Start a form tag that points the action to an url. This form tag will also include the hidden field containing the auth token.

The url options should be given either as a string, or as a url() function. The method for the form defaults to POST.

Options:

multipart
If set to True, the enctype is set to “multipart/form-data”.
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.

webhelpers.html.tags

webhelpers.html.tags.form(url, method='post', multipart=False, **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:

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

Examples:

>>> 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"><input name="_method" type="hidden" value="put" />')
>>> form("/submit", "post", multipart=True) 
literal(u'<form action="/submit" enctype="multipart/form-data" method="post">')
webhelpers.html.tags.end_form()

Output “</form>”.

Example:

>>> end_form()
literal(u'</form>')
webhelpers.html.tags.text(name, value=None, **attrs)

Create a standard text field.

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

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.

webhelpers.html.tags.hidden(name, value=None, **attrs)
Create a hidden field.
webhelpers.html.tags.file(name, value=None, **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 name="myfile" type="file" />')
webhelpers.html.tags.password(name, value=None, **attrs)

Create a password field.

Takes the same options as text_field.

webhelpers.html.tags.textarea(name, content='', **attrs)

Create a text input area.

Example:

>>> textarea("body", "", cols=25, rows=10)
literal(u'<textarea cols="25" name="body" rows="10"></textarea>')
webhelpers.html.tags.checkbox(name, value='1', checked=False, label=None, **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.

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().

Example:

>>> checkbox("hi")
literal(u'<input name="hi" type="checkbox" value="1" />')
webhelpers.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.

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.

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

webhelpers.html.tags.submit(name, value, **attrs)
Create a submit button with the text value as the caption.
webhelpers.html.tags.select(name, selected_values, options, **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.

    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

    selections.

  • 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 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 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 name="currency">\n<option selected="selected" value="">Please choose ...</option>\n<option value="$">Dollar</option>\n<option value="DKK">Kroner</option>\n</select>')
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.

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.

text(name, **kw)
Build a text box.
textarea(name, **kw)
Build a rectangular text area.

Create a hyperlink with the given text pointing to the URL.

If the label is None or empty, the URL will be used as the label.

This function does not modify the URL in any way. The label will be escaped if it contains HTML markup. To prevent escaping, wrap the label in a webhelpers.html.literal().

Same as link_to but return just the label if the condition is false.

This is useful in a menu when you don’t want the current option to be a link. The condition will be something like: actual_value != value_of_this_menu_item.

Same as link_to but return just the label if the condition is true.
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.

Examples:

>>> 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>')
webhelpers.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

Examples:

>>> 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" />')

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.

Examples:

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

Examples:

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

Examples:

>>> 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" />')

webhelpers.html.tools

webhelpers.html.tools.button_to(name, url='', **html_options)

Generate a form containing a sole button that submits to url.

Use this method instead of link_to for actions that do not have the safe HTTP GET semantics implied by using a hypertext link.

The parameters are the same as for link_to. Any html_options that you pass will be applied to the inner input element. In particular, pass

disabled = True/False

as part of html_options to control whether the button is disabled. The generated form element is given the class ‘button-to’, to which you can attach CSS styles for display purposes.

The submit button itself will be displayed as an image if you provide both type and src as followed:

type=’image’, src=’icon_delete.gif’

The src path should be the exact URL desired. A previous version of this helper added magical prefixes but this is no longer the case.

Example 1:

# inside of controller for "feeds"
>> button_to("Edit", url(action='edit', id=3))
<form method="POST" action="/feeds/edit/3" class="button-to">
<div><input value="Edit" type="submit" /></div>
</form>

Example 2:

>> button_to("Destroy", url(action='destroy', id=3), 
.. method='DELETE')
<form method="POST" action="/feeds/destroy/3" 
 class="button-to">
<div>
    <input type="hidden" name="_method" value="DELETE" />
    <input value="Destroy" type="submit" />
</div>
</form>

Example 3:

# Button as an image.
>> button_to("Edit", url(action='edit', id=3), type='image', 
.. src='icon_delete.gif')
<form method="POST" action="/feeds/edit/3" class="button-to">
<div><input alt="Edit" src="/images/icon_delete.gif"
 type="image" value="Edit" /></div>
</form>

Note

This method generates HTML code that represents a form. Forms are “block” content, which means that you should not try to insert them into your HTML where only inline content is expected. For example, you can legally insert a form inside of a div or td element or in between p elements, but not in the middle of a run of text, nor can you place a form within another form. (Bottom line: Always validate your HTML before going public.)

webhelpers.html.tools.mail_to(email_address, name=None, cc=None, bcc=None, subject=None, body=None, replace_at=None, replace_dot=None, encode=None, **html_options)

Create a link tag for starting an email to the specified email_address.

This email_address is also used as the name of the link unless name is specified. Additional HTML options, such as class or id, can be passed in the html_options hash.

You can also make it difficult for spiders to harvest email address by obfuscating them.

Examples:

>>> mail_to("me@domain.com", "My email", encode = "javascript")
literal(u'<script type="text/javascript">\n//<![CDATA[\neval(unescape(\'%64%6f%63%75%6d%65%6e%74%2e%77%72%69%74%65%28%27%3c%61%20%68%72%65%66%3d%22%6d%61%69%6c%74%6f%3a%6d%65%40%64%6f%6d%61%69%6e%2e%63%6f%6d%22%3e%4d%79%20%65%6d%61%69%6c%3c%2f%61%3e%27%29%3b\'))\n//]]>\n</script>')

>>> mail_to("me@domain.com", "My email", encode = "hex")
literal(u'<a href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;%6d%65@%64%6f%6d%61%69%6e.%63%6f%6d">My email</a>')

You can also specify the cc address, bcc address, subject, and body parts of the message header to create a complex e-mail using the corresponding cc, bcc, subject, and body keyword arguments. Each of these options are URI escaped and then appended to the email_address before being output. Be aware that javascript keywords will not be escaped and may break this feature when encoding with javascript.

Examples:

>>> mail_to("me@domain.com", "My email", cc="ccaddress@domain.com", bcc="bccaddress@domain.com", subject="This is an example email", body= "This is the body of the message.")
literal(u'<a href="mailto:me@domain.com?cc=ccaddress%40domain.com&amp;bcc=bccaddress%40domain.com&amp;subject=This%20is%20an%20example%20email&amp;body=This%20is%20the%20body%20of%20the%20message.">My email</a>')
webhelpers.html.tools.highlight(text, phrase, highlighter='<strong class="highlight">1</strong>')

Highlight the phrase where it is found in the text.

The highlighted phrase will be surrounded by the highlighter, by default:

<strong class="highlight">I'm a highlight phrase</strong>
highlighter
Defines the highlighting phrase. This argument should be a single-quoted string with \1 where the phrase is supposed to be inserted.

Note: The phrase is sanitized to include only letters, digits, and spaces before use.

Example:

>>> highlight('You searched for: Pylons', 'Pylons')
'You searched for: <strong class="highlight">Pylons</strong>'

Turn all urls and email addresses into clickable links.

link
Used to determine what to link. Options are “all”, “email_addresses”, or “urls”

Example:

>>> auto_link("Go to http://www.planetpython.com and say hello to guido@python.org")
literal(u'Go to <a href="http://www.planetpython.com">http://www.planetpython.com</a> and say hello to <a href="mailto:guido@python.org">guido@python.org</a>')

Strip link tags from text leaving just the link label.

Example:

>>> strip_links('<a href="something">else</a>')
'else'