Latest Version: 0.9.6.2

rails

Helper functions ported from Rails


Attributes

a javascript_builtins

('prototype.js', 'scriptaculous.js')

a javascript_path

'/Users/bbangert/Programming/Python/WebHelpers/webhelpers/rails/javascripts'

Functions

f auto_discovery_link_tag(source, type='rss', **kwargs) ...

Returns a link tag allowing browsers and news readers (that support it) to auto-detect an RSS or ATOM feed for current page.

source
The URL of the feed. The URL is ultimately prepended with the environment's SCRIPT_NAME (the root path of the web application), unless the URL is fully-fledged (e.g. http://example.com).
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_tag('http://feed.com/feed.xml')
'<link href="http://feed.com/feed.xml" rel="alternate" title="RSS" type="application/rss+xml" />'

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

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

>>> auto_discovery_link_tag('/app.html', type='text/html')
'<link href="/app.html" rel="alternate" title="" type="text/html" />'

f auto_link(text, link='all', **href_options) ...

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

f button_to(name, url='', **html_options) ...

Generates a form containing a sole button that submits to the URL given by 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 will be computed as the image_tag() computes it's source argument.

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), confirm="Are you sure?", method='DELETE')
<form method="POST" action="/feeds/destroy/3" class="button-to">
<div>
    <input type="hidden" name="_method" value="DELETE" />
    <input onclick="return confirm('Are you sure?');" 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.)

f button_to_function(name, function, **html_options) ...

Returns a link that'll trigger a JavaScript function using the onclick handler and return false after the fact.

Example:

button_to_function("Greeting", "alert('Hello world!')")

f camelize(name) ...

Camelize a name

f cdata_section(content) ...

Returns a CDATA section with the given content.

CDATA sections are used to escape blocks of text containing characters which would otherwise be recognized as markup. CDATA sections begin with the string <![CDATA[ and end with (and may not contain) the string ]]>.

f check_box(name, value='1', checked=False, **options) ...

Creates a check box.

f content_tag(name, content, **options) ...

Create a tag with content

Takes the same keyword args as tag

Examples:

>>> content_tag("p", "Hello world!")
'<p>Hello world!</p>'
>>> content_tag("div", content_tag("p", "Hello world!"), class_="strong")
'<div class="strong"><p>Hello world!</p></div>'

f counter(name='default', start=1, step=1) ...

Return the next cardinal in a sequence.

Every time counter is called, the value returned will be the next counting number in that sequence. This is reset to start on every request, but can also be reset by calling reset_counter().

You can optionally specify the number you want to start at by passing in the start argument (defaults to 1).

You can also optionally specify the step size you want by passing in the step argument (defaults to 1).

Sequences will increase monotonically by step each time it is called, until the heat death of the universe or python explodes.

This can be used to count rows in a table:

# In Myghty
% for item in items:
<tr>
    <td><% h.counter() %></td>
</tr>
% #endfor

You can use named counters to prevent clashes in nested loops. You'll have to reset the inner cycle manually though. See the documentation for webhelpers.text.cycle() for a similar example.

f current_page(url) ...

Returns true if the current page uri is equivalent to url

f current_url(*args, **kwargs) ...

Returns the current page's url.

f cycle(*args, **kargs) ...

Returns the next cycle of the given list

Everytime cycle is called, the value returned will be the next item in the list passed to it. This list is reset on every request, but can also be reset by calling reset_cycle().

You may specify the list as either arguments, or as a single list argument.

This can be used to alternate classes for table rows:

# In Myghty...
% for item in items:
<tr class="<% cycle("even", "odd") %>">
    ... use item ...
</tr>
% #endfor

You can use named cycles to prevent clashes in nested loops. You'll have to reset the inner cycle, manually:

% for item in items:
<tr class="<% cycle("even", "odd", name="row_class") %>
    <td>
%     for value in item.values:
        <span style="color:'<% cycle("red", "green", "blue",
                                     name="colors") %>'">
                    item
        </span>
%     #endfor
    <% reset_cycle("colors") %>
    </td>
</tr>
% #endfor

f distance_of_time_in_words(from_time, to_time=0, include_seconds=False) ...

Reports the approximate distance in time between two datetime objects or integers as seconds.

Set include_seconds to True for more more detailed approximations when distance < 1 min, 29 secs

Distances are reported based on the following table:

0 <-> 29 secs => less than a minute 30 secs <-> 1 min, 29 secs => 1 minute 1 min, 30 secs <-> 44 mins, 29 secs => [2..44] minutes 44 mins, 30 secs <-> 89 mins, 29 secs => about 1 hour 89 mins, 29 secs <-> 23 hrs, 59 mins, 29 secs => about [2..24] hours 23 hrs, 59 mins, 29 secs <-> 47 hrs, 59 mins, 29 secs => 1 day 47 hrs, 59 mins, 29 secs <-> 29 days, 23 hrs, 59 mins, 29 secs => [2..29] days 29 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs => about 1 month 59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 31 secs => [2..12] months 1 yr minus 30 secs <-> 2 yrs minus 31 secs => about 1 year 2 yrs minus 30 secs <-> max time or date => over [2..X] years

With include_seconds set to True and the difference < 1 minute 29 seconds:

0-4 secs => less than 5 seconds 5-9 secs => less than 10 seconds 10-19 secs => less than 20 seconds 20-39 secs => half a minute 40-59 secs => less than a minute 60-89 secs => 1 minute

Examples:

>>> from datetime import datetime, timedelta
>>> from_time = datetime.now()
>>> distance_of_time_in_words(from_time, from_time + timedelta(minutes=50))
'about 1 hour'
>>> distance_of_time_in_words(from_time, from_time + timedelta(seconds=15))
'less than a minute'
>>> distance_of_time_in_words(from_time, from_time + timedelta(seconds=15), include_seconds=True)
'less than 20 seconds'

Note: distance_of_time_in_words calculates one year as 365.25 days.

f draggable_element(element_id, **options) ...

Makes the element with the DOM ID specified by element_id draggable.

Example:

<% draggable_element("my_image", revert=True)

You can change the behaviour with various options, see http://script.aculo.us for more documentation.

f drop_receiving_element(element_id, **options) ...

Makes an element able to recieve dropped draggable elements

Makes the element with the DOM ID specified by element_id receive dropped draggable elements (created by draggable_element) and make an AJAX call By default, the action called gets the DOM ID of the element as parameter.

Example:

<% drop_receiving_element("my_cart", url=url_for(controller="cart", action="add" )) %>

You can change the behaviour with various options, see http://script.aculo.us for more documentation.

f end_form() ...

Outputs "</form>"

Example:

>>> end_form()
'</form>'

f escape_javascript(javascript) ...

Escape carriage returns and single and double quotes for JavaScript segments.

f escape_once(html) ...

Escapes a given string without affecting existing escaped entities.

>>> escape_once("1 < 2 &amp; 3")
'1 &lt; 2 &amp; 3'

f evaluate_remote_response() ...

Returns a Javascript function that evals a request response

Returns 'eval(request.responseText)' which is the JavaScript function that form_remote_tag can call in complete to evaluate a multiple update return document using update_element_function calls.

f excerpt(text, phrase, radius=100, excerpt_string='...') ...

Extracts an excerpt from the text. Returns an empty string if the phrase isn't found.

phrase
Phrase to excerpt from text
radius
How many surrounding characters to include
excerpt_string
Characters surrounding entire excerpt

Example:

>>> excerpt("hello my world", "my", 3)
'...lo my wo...'

f file_field(name, value=None, **options) ...

Creates 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_field('myfile')
'<input id="myfile" name="myfile" type="file" />'

f form(url, method='POST', multipart=False, **options) ...

Starts a form tag that points the action to an url.

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.

f form_remote_tag(**options) ...

Create a form tag using a remote function to submit the request

Returns a form tag that will submit using XMLHttpRequest in the background instead of the regular reloading POST arrangement. Even though it's using JavaScript to serialize the form elements, the form submission will work just like a regular submission as viewed by the receiving side. The options for specifying the target with url and defining callbacks is the same as link_to_remote.

A "fall-through" target for browsers that doesn't do JavaScript can be specified with the action/method options on html.

Example:

form_remote_tag(html=dict(action=url(
                            controller="some", action="place")))

By default the fall-through action is the same as the one specified in the url (and the default method is POST).

f hidden_field(name, value=None, **options) ...

Creates a hidden field.

Takes the same options as text_field

f highlight(text, phrase, highlighter='<strong class="highlight">\\1</strong>', hilighter=None) ...

Highlights 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>'

f human_size(*args, **kwargs) ...

Deprecated: Use number_to_human_size instead.

f image_tag(source, alt=None, size=None, **options) ...

Returns an image tag for the specified source.

source
The source URL of the image. The URL is prepended with '/images/', unless its full path is specified. The URL is ultimately prepended with the environment's SCRIPT_NAME (the root path of the web application), unless the URL is fully-fledged (e.g. http://example.com).
alt
The img's alt tag. Defaults to the source's filename, title cased.
size
The img's size, specified in the format "XxY". "30x45" becomes width="30", height="45". "x20" becomes height="20".

Examples:

>>> image_tag('xml.png')
'<img alt="Xml" src="/images/xml.png" />'

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

>>> image_tag("icon.png", size="16x10", alt="Edit Entry")
'<img alt="Edit Entry" height="10" src="/images/icon.png" width="16" />'

>>> image_tag("/icons/icon.gif", size="16x16")
'<img alt="Icon" height="16" src="/icons/icon.gif" width="16" />'

>>> image_tag("/icons/icon.gif", size="16x")
'<img alt="Icon" src="/icons/icon.gif" width="16" />'

f javascript_include_tag(*sources, **options) ...

Returns script include tags for the specified javascript sources.

Each source's URL path is prepended with '/javascripts/' unless their full path is specified. Each source's URL path is ultimately prepended with the environment's SCRIPT_NAME (the root path of the web application), unless the URL path is a full-fledged URL (e.g. http://example.com). Sources with no filename extension will be appended with the '.js' extension.

Optionally includes (prepended) WebHelpers' built-in javascripts when passed the builtins=True keyword argument.

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

Examples:

>>> print javascript_include_tag(builtins=True)
<script src="/javascripts/prototype.js" type="text/javascript"></script>
<script src="/javascripts/scriptaculous.js" type="text/javascript"></script>

>>> print javascript_include_tag(builtins=True, defer=True)
<script defer="defer" src="/javascripts/prototype.js" type="text/javascript"></script>
<script defer="defer" src="/javascripts/scriptaculous.js" type="text/javascript"></script>

>>> print javascript_include_tag('prototype', '/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_include_tag('app', '/test/test.1.js', builtins=True)
<script src="/javascripts/prototype.js" type="text/javascript"></script>
<script src="/javascripts/scriptaculous.js" type="text/javascript"></script>
<script src="/javascripts/app.js" type="text/javascript"></script>
<script src="/test/test.1.js" type="text/javascript"></script>

f javascript_tag(content, **html_options) ...

Returns a JavaScript tag with the content inside.

Example:

>>> javascript_tag("alert('All is good')")
'<script type="text/javascript">\n//<![CDATA[\nalert(\'All is good\')\n//]]>\n</script>'

f js_obfuscate(data) ...

Obfuscates data in a Javascript tag

Example:

>>> js_obfuscate("<input type='hidden' name='check' value='valid' />")
'<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%69%6e%70%75%74%20%74%79%70%65%3d%27%68%69%64%64%65%6e%27%20%6e%61%6d%65%3d%27%63%68%65%63%6b%27%20%76%61%6c%75%65%3d%27%76%61%6c%69%64%27%20%2f%3e%27%29%3b\'))\n//]]>\n</script>'

f link_to(name, url='', **html_options) ...

Creates a link tag of the given name using an URL created by the set of options.

See the valid options in the documentation for Routes url_for.

The html_options has three special features. One for creating javascript confirm alerts where if you pass confirm='Are you sure?' , the link will be guarded with a JS popup asking that question. If the user accepts, the link is processed, otherwise not.

Another for creating a popup window, which is done by either passing popup with True or the options of the window in Javascript form.

And a third for making the link do a POST request (instead of the regular GET) through a dynamically added form element that is instantly submitted. Note that if the user has turned off Javascript, the request will fall back on the GET. So its your responsibility to determine what the action should be once it arrives at the controller. The POST form is turned on by passing post as True. Note, it's not possible to use POST requests and popup targets at the same time (an exception will be thrown).

Examples:

>> link_to("Delete this page", url(action="destroy", id=4), confirm="Are you sure?")
>> link_to("Help", url(action="help"), popup=True)
>> link_to("Busy loop", url(action="busy"), popup=['new_window', 'height=300,width=600'])
>> link_to("Destroy account", url(action="destroy"), confirm="Are you sure?", method='delete')

f link_to_function(name, function, **html_options) ...

Returns a link that'll trigger a JavaScript function using the onclick handler and return false after the fact.

Example:

link_to_function("Greeting", "alert('Hello world!')")

f link_to_if(condition, name, url, **html_options) ...

Conditionally create a link tag of the given name using the url

If condition is True only the name is returned.

f link_to_remote(name, options=None, **html_options) ...

Links to a remote function

Returns a link to a remote action defined dict(url=url()) (using the url() format) that's called in the background using XMLHttpRequest. The result of that request can then be inserted into a DOM object whose id can be specified with the update keyword.

Any keywords given after the second dict argument are considered html options and assigned as html attributes/values for the element.

Example:

link_to_remote("Delete this post", dict(update="posts",
               url=url(action="destroy", id=post.id)))

You can also specify a dict for update to allow for easy redirection of output to an other DOM element if a server-side error occurs:

Example:

link_to_remote("Delete this post",
        dict(url=url(action="destroy", id=post.id),
             update=dict(success="posts", failure="error")))

Optionally, you can use the position parameter to influence how the target DOM element is updated. It must be one of 'before', 'top', 'bottom', or 'after'.

By default, these remote requests are processed asynchronous during which various JavaScript callbacks can be triggered (for progress indicators and the likes). All callbacks get access to the request object, which holds the underlying XMLHttpRequest.

To access the server response, use request.responseText, to find out the HTTP status, use request.status.

Example:

link_to_remote(word,
        dict(url=url(action="undo", n=word_counter),
             complete="undoRequestCompleted(request)"))

The callbacks that may be specified are (in order):

loading
Called when the remote document is being loaded with data by the browser.
loaded
Called when the browser has finished loading the remote document.
interactive
Called when the user can interact with the remote document, even though it has not finished loading.
success
Called when the XMLHttpRequest is completed, and the HTTP status code is in the 2XX range.
failure
Called when the XMLHttpRequest is completed, and the HTTP status code is not in the 2XX range.
complete
Called when the XMLHttpRequest is complete (fires after success/failure if they are present).

You can further refine success and failure by adding additional callbacks for specific status codes.

Example:

link_to_remote(word,
        dict(url=url(action="action"),
             404="alert('Not found...? Wrong URL...?')",
             failure="alert('HTTP Error ' + request.status + '!')"))

A status code callback overrides the success/failure handlers if present.

If you for some reason or another need synchronous processing (that'll block the browser while the request is happening), you can specify type='synchronous'.

You can customize further browser side call logic by passing in JavaScript code snippets via some optional parameters. In their order of use these are:

confirm
Adds confirmation dialog.
condition
Perform remote request conditionally by this expression. Use this to describe browser-side conditions when request should not be initiated.
before
Called before request is initiated.
after
Called immediately after request was initiated and before loading.
submit
Specifies the DOM element ID that's used as the parent of the form elements. By default this is the current form, but it could just as well be the ID of a table row or any other DOM element.

f link_to_unless(condition, name, url, **html_options) ...

Conditionally create a link tag of the given name using the url

If condition is True only the name is returned.

f link_to_unless_current(name, url, **html_options) ...

Conditionally create a link tag of the given name using the url

If the current request uri is the same as the link's only the name is returned. This is useful for creating link bars where you don't want to link to the page currently being viewed.

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

Creates a link tag for starting an email to the specified email_address, which 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")
'<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")
'<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.")
'<a href="mailto:me@domain.com?cc=ccaddress%40domain.com&amp;body=This%20is%20the%20body%20of%20the%20message.&amp;subject=This%20is%20an%20example%20email&amp;bcc=bccaddress%40domain.com">My email</a>'

f markdown(text, **kwargs) ...

Format the text with MarkDown formatting

This function uses the Python MarkDown library which is included with WebHelpers.

f number_to_currency(number, unit='$', precision=2, separator='.', delimiter=',') ...

Formats a number into a currency string.

precision
Indicates the level of precision. Defaults to 2
unit
Sets the currency type, defaults to "$"
separator
Used to set what the unit separation should be. Defaults to "."
delimiter
The delimiter character to use, defaults to ","

Examples:

>>> number_to_currency(1234567890.50)
'$1,234,567,890.50'
>>> number_to_currency(1234567890.506)
'$1,234,567,890.51'
>>> number_to_currency(1234567890.50, unit="&pound;", separator=",", delimiter="")
'&pound;1234567890,50'

f number_to_human_size(size, precision=1) ...

Returns a formatted-for-humans file size.

precision
The level of precision, defaults to 1

Examples:

>>> number_to_human_size(123)
'123 Bytes'
>>> number_to_human_size(1234)
'1.2 KB'
>>> number_to_human_size(12345)
'12.1 KB'
>>> number_to_human_size(1234567)
'1.2 MB'
>>> number_to_human_size(1234567890)
'1.1 GB'
>>> number_to_human_size(1234567890123)
'1.1 TB'
>>> number_to_human_size(1234567, 2)
'1.18 MB'

f number_to_percentage(number, precision=3, separator='.') ...

Formats a number as into a percentage string.

precision
The level of precision, defaults to 3
separator
The unit separator to be used. Defaults to "."

Examples:

>>> number_to_percentage(100)
'100.000%'
>>> number_to_percentage(100, precision=0)
'100%'
>>> number_to_percentage(302.0574, precision=2)
'302.06%'

f number_to_phone(number, area_code=False, delimiter='-', extension='', country_code='') ...

Formats a number into a US phone number string.

area_code
When enabled, adds parentheses around the area code. Defaults to False
delimiter
The delimiter to use, defaults to "-"
extension
Specifies an extension to add to the end of the generated number
country_code
Sets the country code for the phone number

Examples:

>>> number_to_phone(1235551234)
'123-555-1234'
>>> number_to_phone(1235551234, area_code=True)
'(123) 555-1234'
>>> number_to_phone(1235551234, delimiter=" ")
'123 555 1234'
>>> number_to_phone(1235551234, area_code=True, extension=555)
'(123) 555-1234 x 555'
>>> number_to_phone(1235551234, country_code=1)
'1-123-555-1234'

f number_with_delimiter(number, delimiter=',', separator='.') ...

Formats a number with grouped thousands using delimiter.

delimiter
The delimiter character to use, defaults to ","
separator
Used to set what the unit separation should be. Defaults to "."

Example:

>>> number_with_delimiter(12345678)
'12,345,678'
>>> number_with_delimiter(12345678.05)
'12,345,678.05'
>>> number_with_delimiter(12345678, delimiter=".")
'12.345.678'

f number_with_precision(number, precision=3) ...

Formats a number with a level of precision.

precision
The level of precision, defaults to 3

Example:

>>> number_with_precision(111.2345)
'111.234'
>>> number_with_precision(111.2345, 2)
'111.23'

f observe_field(field_id, **options) ...

Observes the field with the DOM ID specified by field_id and makes an Ajax call when its contents have changed.

Required keyword args are:

url
url()-style options for the action to call when the field has changed.

Additional keyword args are:

frequency
The frequency (in seconds) at which changes to this field will be detected. Not setting this option at all or to a value equal to or less than zero will use event based observation instead of time based observation.
update
Specifies the DOM ID of the element whose innerHTML should be updated with the XMLHttpRequest response text.
with_
A JavaScript expression specifying the parameters for the XMLHttpRequest. This defaults to 'value', which in the evaluated context refers to the new field value.

Additionally, you may specify any of the options documented in link_to_remote.

f observe_form(form_id, **options) ...

Like observe_field, but operates on an entire form identified by the DOM ID form_id.

Keyword args are the same as observe_field, except the default value of the with_ keyword evaluates to the serialized (request string) value of the form.

f options_for_select(container, selected=None) ...

Creates select options from a container (list, tuple, dict)

Accepts a container (list, tuple, dict) and returns a string of option tags. Given a container where the elements respond to first and last (such as a two-element array), the "lasts" serve as option values and the "firsts" as option text. Dicts are turned into this form automatically, so the keys become "firsts" and values become lasts. If selected is specified, the matching "last" or element will get the selected option-tag. Selected may also be an array of values to be selected when using a multiple select.

Examples (call, result):

>>> options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
'<option value="$">Dollar</option>\n<option value="DKK">Kroner</option>'
>>> options_for_select([ "VISA", "MasterCard" ], "MasterCard")
'<option value="VISA">VISA</option>\n<option value="MasterCard" selected="selected">MasterCard</option>'
>>> options_for_select(dict(Basic="$20", Plus="$40"), "$40")
'<option value="$40" selected="selected">Plus</option>\n<option value="$20">Basic</option>'
>>> options_for_select([ "VISA", "MasterCard", "Discover" ], ["VISA", "Discover"])
'<option value="VISA" selected="selected">VISA</option>\n<option value="MasterCard">MasterCard</option>\n<option value="Discover" selected="selected">Discover</option>'

Note: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.

f options_for_select_from_dicts(container, name_key, value_key=None, selected=None) ...

Create select options from dicts in a container

Returns a string of option tags that have been compiled by iterating over the container and assigning the the result of a call to the value_key as the option value and the name_attr as the option text. If selected is specified, the element returning a match on value_key will get the selected option tag.

NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.

f options_for_select_from_objects(container, name_attr, value_attr=None, selected=None) ...

Create select options from objects in a container

Returns a string of option tags that have been compiled by iterating over the container and assigning the the result of a call to the value_attr as the option value and the name_attr as the option text. If selected is specified, the element returning a match on value_attr will get the selected option tag.

NOTE: Only the option tags are returned, you have to wrap this call in a regular HTML select tag.

f parallel_effects(*effects, **js_options) ...

Wraps visual effects so they occur in parallel

Example:

parallel_effects(
    visual_effect('highlight, 'dom_id'),
    visual_effect('fade', 'dom_id'),
)

f password_field(name='password', value=None, **options) ...

Creates a password field

Takes the same options as text_field

f periodically_call_remote(**options) ...

Periodically calls a remote function

Periodically calls the specified url every frequency seconds (default is 10). Usually used to update a specified div update with the results of the remote call. The options for specifying the target with url and defining callbacks is the same as link_to_remote.

f radio_button(name, value, checked=False, **options) ...

Creates a radio button.

The id of the radio button will be set to the name + value with a _ in between to ensure its uniqueness.

f remote_function(**options) ...

Returns the JavaScript needed for a remote function.

Takes the same options that can be passed as options to link_to_remote.

Example:

<select id="options" onchange="<% remote_function(update="options",
        url=url(action='update_options')) %>">
    <option value="0">Hello</option>
    <option value="1">World</option>
</select>

f reset_counter(name='default') ...

Resets a counter.

Resets the counter so that it starts from the start cardinal in the sequence next time it is used.

f reset_cycle(name='default') ...

Resets a cycle

Resets the cycle so that it starts from the first element in the array the next time it is used.

f secure_form(url, **args) ...

Create a form tag (like webhelpers.rails.form_tag.form) including a hidden authentication token field.

f secure_form_remote_tag(**args) ...

Create a form tag (like webhelpers.rails.prototype.form_remote_tag) including a hidden authentication token field.

f select(name, option_tags='', **options) ...

Creates a dropdown selection box

option_tags is a string containing the option tags for the select box:

>>> select("people", "<option>George</option>")
'<select id="people" name="people"><option>George</option></select>'

Options:

  • multiple - If set to true the selection will allow multiple choices.

f simple_format(text) ...

Returns text transformed into HTML using very simple formatting rules

Two or more consecutive newlines(\n\n) are considered as a paragraph and wrapped in <p> tags. One newline (\n) is considered a linebreak and a <br /> tag is appended. This method does not remove the newlines from the text.

f sortable_element(element_id, **options) ...

Makes the element with the DOM ID specified by element_id sortable.

Uses drag-and-drop and makes an Ajax call whenever the sort order has changed. By default, the action called gets the serialized sortable element as parameters.

Example:

<% sortable_element("my_list", url=url(action="order")) %>

In the example, the server-side action gets a "my_list" array parameter containing the values of the ids of elements the sortable consists of, in the current order (like mylist=item1&mylist=item2, where item1 and item2 are the ids of the <li> elements).

Note: For this to work, the sortable elements must have id attributes in the form string_identifier. For example, item_1. Only the identifier part of the id attribute will be serialized.

You can change the behaviour with various options, see http://script.aculo.us for more documentation.

f start_form(url, method='POST', multipart=False, **options) ...

Starts a form tag that points the action to an url.

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.

f strip_links(text) ...

Strips link tags from text leaving just the link label.

Example:

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

f stylesheet_link_tag(*sources, **options) ...

Returns CSS link tags for the specified stylesheet sources.

Each source's URL path is prepended with '/stylesheets/' unless their full path is specified. Each source's URL path is ultimately prepended with the environment's SCRIPT_NAME (the root path of the web application), unless the URL path is a full-fledged URL (e.g. http://example.com). Sources with no filename extension will be appended with the '.css' extension.

Examples:

>>> stylesheet_link_tag('style')
'<link href="/stylesheets/style.css" media="screen" rel="Stylesheet" type="text/css" />'

>>> stylesheet_link_tag('dir/file', media='all')
'<link href="/stylesheets/dir/file.css" media="all" rel="Stylesheet" type="text/css" />'

>>> stylesheet_link_tag('/dir/file', media='all')
'<link href="/dir/file.css" media="all" rel="Stylesheet" type="text/css" />'

f submit(value='Save changes', name='commit', confirm=None, disable_with=None, **options) ...

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

Options:

  • confirm - A confirm message displayed when the button is clicked.
  • disable_with - The value to be used to rename a disabled version of the submit button.

f submit_to_remote(name, value, **options) ...

A submit button that submits via an XMLHttpRequest call

Returns a button input tag that will submit form using XMLHttpRequest in the background instead of regular reloading POST arrangement. Keyword args are the same as in form_remote_tag.

f tag(name, open=False, **options) ...

Returns an XHTML compliant tag of type name.

open
Set to True if the tag should remain open

All additional keyword args become attribute/value's for the tag. To pass in Python reserved words, append _ to the name of the key. For attributes with no value (such as disabled and readonly), a value of True is permitted.

Examples:

>>> tag("br")
'<br />'
>>> tag("br", True)
'<br>'
>>> tag("input", type="text")
'<input type="text" />'
>>> tag("input", type='text', disabled=True)
'<input disabled="disabled" type="text" />'

f text_area(name, content='', **options) ...

Creates a text input area.

Options:

  • size - A string specifying the dimensions of the textarea.

Example:

>>> text_area("body", '', size="25x10")
'<textarea cols="25" id="body" name="body" rows="10"></textarea>'

f text_field(name, value=None, **options) ...

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

Remaining keyword options will be standard HTML options for the tag.

f textilize(text, sanitize=False) ...

Format the text 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.

f time_ago_in_words(from_time, include_seconds=False) ...

Like distance_of_time_in_words, but where to_time is fixed to datetime.now().

f truncate(text, length=30, truncate_string='...') ...

Truncates text with replacement characters

length
The maximum length of text before replacement
truncate_string
If text exceeds the length, this string will replace the end of the string

Example:

>>> truncate('Once upon a time in a world far far away', 14)
'Once upon a...'

f update_element_function(element_id, **options) ...

Returns a JavaScript function (or expression) that'll update a DOM element.

content
The content to use for updating.
action
Valid options are 'update' (assumed by default), 'empty', 'remove'
position
If the action is 'update', you can optionally specify one of the following positions: 'before', 'top', 'bottom', 'after'.

Example:

<% javascript_tag(update_element_function("products",
    position='bottom', content="<p>New product!</p>")) %>

This method can also be used in combination with remote method call where the result is evaluated afterwards to cause multiple updates on a page. Example:

# Calling view
<% form_remote_tag(url=url(action="buy"),
        complete=evaluate_remote_response()) %>
    all the inputs here...

# Controller action
def buy(self, **params):
    c.product = Product.find(1)
    return render_response('/buy.myt')

# Returning view (buy.myt)
<% update_element_function(
        "cart", action='update', position='bottom',
        content="<p>New Product: %s</p>" % c.product.name) %>
<% update_element_function("status", binding='binding',
        content="You've bought a new product!") %>

f url(*args, **kargs) ...

Lazily evaluates url_for() arguments

Used instead of url_for() for functions so that the function will be evaluated in a lazy manner rather than at initial function call.

f visual_effect(name, element_id=False, **js_options) ...

Returns a JavaScript snippet to be used on the Ajax callbacks for starting visual effects.

Example:

<% link_to_remote("Reload",
        dict(url=url(action="reload"),
             update="posts",
             complete=visual_effect('highlight', "posts", duration=0.5))) %>

If no element_id is given, it assumes "element" which should be a local variable in the generated JavaScript execution context. This can be used for example with drop_receiving_element:

<% drop_receving_element('some_element', loading=visual_effect('fade')) %>

This would fade the element that was dropped on the drop receiving element.

For toggling visual effects, you can use toggle_appear, toggle_slide, and toggle_blind which will alternate between appear/fade, slidedown/slideup, and blinddown/blindup respectively.

You can change the behaviour with various options, see http://script.aculo.us for more documentation.

f word_wrap(text, line_width=80) ...

Wraps text into lines no longer than line_width width. This function breaks on the first whitespace character that does not exceed line_width.

Deprecated: Use python's builtin textwrap.fill instead.

Modules

The webhelpers.rails module exposes 12 submodules:

asset_tag
Asset Tag Helpers
date
Date/Time Helpers
form_options
Form Options Helpers
form_tag
Form Tag Helpers
javascript
Javascript Helpers
number
Number Helpers
prototype
Prototype Helpers
scriptaculous
Scriptaculous Helpers
secure_form_tag
Secure Form Tag Helpers -- For prevention of Cross-site request forgery (CSRF) attacks.
tags
Tag Helpers
text
Text Helpers
urls
URL Helpers

See the source for more information.

Top