The rails module is accessible via the webhelpers module.
Returns a link tag allowing browsers and news readers (that support it) to auto-detect an RSS or ATOM feed for current page.
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" />'
Turns all urls and email addresses into clickable links.
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>'
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.)
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!')")
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 ]]>.
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>'
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.
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
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.
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.
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.
Escape carriage returns and single and double quotes for JavaScript segments.
Escapes a given string without affecting existing escaped entities.
>>> escape_once("1 < 2 & 3")
'1 < 2 & 3'
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.
Extracts an excerpt from the text. Returns an empty string if the phrase isn't found.
Example:
>>> excerpt("hello my world", "my", 3)
'...lo my wo...'
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" />'
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:
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).
Creates a hidden field.
Takes the same options as text_field
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>
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>'
Returns an image tag for the specified source.
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" />'
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>
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>'
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>'
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')
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!')")
Conditionally create a link tag of the given name using the url
If condition is True only the name is returned.
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):
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:
Conditionally create a link tag of the given name using the url
If condition is True only the name is returned.
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.
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="mailto:%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&body=This%20is%20the%20body%20of%20the%20message.&subject=This%20is%20an%20example%20email&bcc=bccaddress%40domain.com">My email</a>'
Format the text with MarkDown formatting
This function uses the Python MarkDown library which is included with WebHelpers.
Formats a number into a currency string.
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="£", separator=",", delimiter="") '£1234567890,50'
Returns a formatted-for-humans file size.
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'
Formats a number as into a percentage string.
Examples:
>>> number_to_percentage(100) '100.000%' >>> number_to_percentage(100, precision=0) '100%' >>> number_to_percentage(302.0574, precision=2) '302.06%'
Formats a number into a US phone number string.
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'
Formats a number with grouped thousands using delimiter.
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'
Formats a number with a level of precision.
Example:
>>> number_with_precision(111.2345) '111.234' >>> number_with_precision(111.2345, 2) '111.23'
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:
Additional keyword args are:
Additionally, you may specify any of the options documented in link_to_remote.
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.
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.
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.
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.
Wraps visual effects so they occur in parallel
Example:
parallel_effects(
visual_effect('highlight, 'dom_id'),
visual_effect('fade', 'dom_id'),
)
Creates a password field
Takes the same options as text_field
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.
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.
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>
Resets a counter.
Resets the counter so that it starts from the start cardinal in the sequence next time it is used.
Resets a cycle
Resets the cycle so that it starts from the first element in the array the next time it is used.
Create a form tag (like webhelpers.rails.form_tag.form) including a hidden authentication token field.
Create a form tag (like webhelpers.rails.prototype.form_remote_tag) including a hidden authentication token field.
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:
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.
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.
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:
Strips link tags from text leaving just the link label.
Example:
>>> strip_links('<a href="something">else</a>')
'else'
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" />'
Creates a submit button with the text value as the caption.
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.
Returns an XHTML compliant tag of type name.
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" />'
Creates a text input area.
Options:
Example:
>>> text_area("body", '', size="25x10")
'<textarea cols="25" id="body" name="body" rows="10"></textarea>'
Creates a standard text field.
value is a string, the content of the text field
Options:
Remaining keyword options will be standard HTML options for the tag.
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.
Like distance_of_time_in_words, but where to_time is fixed to datetime.now().
Truncates text with replacement characters
Example:
>>> truncate('Once upon a time in a world far far away', 14)
'Once upon a...'
Returns a JavaScript function (or expression) that'll update a DOM element.
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!") %>
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.
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.
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.
The webhelpers.rails module exposes 12 submodules:
See the source for more information.