Action View Helpers
After reading this guide, you will know:
- How to format dates, strings, and numbers.
- How to work with text and tags.
- How to link to images, videos, stylesheets, etc.
- How to work with Atom feeds and JavaScript in the views.
- How to cache, capture, debug and sanitize content.
The following outlinessome of the most commonly used helpers available inAction View. It serves as a good starting point, but reviewing the fullAPIDocumentation isalso recommended, as it covers all of the helpers in more detail.
1. Formatting
1.1. Dates
These helpers facilitate the display of date and/or time elements as contextualhuman readable forms.
1.1.1. distance_of_time_in_words
Reports the approximate distance in time between twoTime orDate objects orintegers as seconds. Setinclude_seconds to true if you want more detailedapproximations.
distance_of_time_in_words(Time.current,15.seconds.from_now)# => less than a minutedistance_of_time_in_words(Time.current,15.seconds.from_now,include_seconds:true)# => less than 20 secondsWe useTime.current instead ofTime.now because it returns the currenttime based on the timezone set in Rails, whereasTime.now returns a Timeobject based on the server's timezone.
See thedistance_of_time_in_words APIDocumentationfor more information.
1.1.2. time_ago_in_words
Reports the approximate distance in time between aTime orDate object, orinteger as seconds, andTime.current.
time_ago_in_words(3.minutes.from_now)# => 3 minutesSee thetime_ago_in_words APIDocumentationfor more information.
1.2. Numbers
A set of methods for converting numbers into formatted strings. Methods areprovided for phone numbers, currency, percentage, precision, positionalnotation, and file size.
1.2.1. number_to_currency
Formats a number into a currency string (e.g., $13.65).
number_to_currency(1234567890.50)# => $1,234,567,890.50See thenumber_to_currency APIDocumentationfor more information.
1.2.2. number_to_human
Pretty prints (formats and approximates) a number so it is more readable byusers; useful for numbers that can get very large.
number_to_human(1234)# => 1.23 Thousandnumber_to_human(1234567)# => 1.23 MillionSee thenumber_to_human APIDocumentationfor more information.
1.2.3. number_to_human_size
Formats the bytes in size into a more understandable representation; useful forreporting file sizes to users.
number_to_human_size(1234)# => 1.21 KBnumber_to_human_size(1234567)# => 1.18 MBSee thenumber_to_human_size APIDocumentationfor more information.
1.2.4. number_to_percentage
Formats a number as a percentage string.
number_to_percentage(100,precision:0)# => 100%See thenumber_to_percentage APIDocumentationfor more information.
1.2.5. number_to_phone
Formats a number into a phone number (US by default).
number_to_phone(1235551234)# => 123-555-1234See thenumber_to_phone APIDocumentationfor more information.
1.2.6. number_with_delimiter
Formats a number with grouped thousands using a delimiter.
number_with_delimiter(12345678)# => 12,345,678See thenumber_with_delimiter APIDocumentationfor more information.
1.2.7. number_with_precision
Formats a number with the specified level ofprecision, which defaults to 3.
number_with_precision(111.2345)# => 111.235number_with_precision(111.2345,precision:2)# => 111.23See thenumber_with_precision APIDocumentationfor more information.
1.3. Text
A set of methods for filtering, formatting and transforming strings.
1.3.1. excerpt
Given atext and aphrase,excerpt searches for and extracts the firstoccurrence of thephrase, plus the requested surrounding text determined by aradius. An omission marker is prepended/appended if the start/end of theresult does not coincide with the start/end of the text.
excerpt("This is a very beautiful morning","very",separator:" ",radius:1)# => ...a very beautiful...excerpt("This is also an example","an",radius:8,omission:"<chop> ")#=> <chop> is also an exampleSee theexcerpt APIDocumentationfor more information.
1.3.2. pluralize
Returns the singular or plural form of a word based on the value of a number.
pluralize(1,"person")# => 1 personpluralize(2,"person")# => 2 peoplepluralize(3,"person",plural:"users")# => 3 usersSee thepluralize APIDocumentationfor more information.
1.3.3. truncate
Truncates a giventext to a givenlength. If the text is truncated, anomission marker will be appended to the result for a total length not exceedinglength.
truncate("Once upon a time in a world far far away")# => "Once upon a time in a world..."truncate("Once upon a time in a world far far away",length:17)# => "Once upon a ti..."truncate("one-two-three-four-five",length:20,separator:"-")# => "one-two-three..."truncate("And they found that many people were sleeping better.",length:25,omission:"... (continued)")# => "And they f... (continued)"truncate("<p>Once upon a time in a world far far away</p>",escape:false)# => "<p>Once upon a time in a wo..."See thetruncate APIDocumentationfor more information.
1.3.4. word_wrap
Wraps the text into lines no longer thanline_width width.
word_wrap("Once upon a time",line_width:8)# => "Once\nupon a\ntime"See theword_wrap APIDocumentationfor more information.
2. Forms
Form helpers simplify working with models compared to using standard HTMLelements alone. They offer a range of methods tailored to generating forms basedon your models. Some methods correspond to a specific type of input, such astext fields, password fields, select dropdowns, and more. When a form issubmitted, the inputs within the form are grouped into the params object andsent back to the controller.
You can learn more about form helpers in theAction View Form HelpersGuide.
3. Navigation
A set of methods to build links and URLs that depend on the routing subsystem.
3.1. button_to
Generates a form that submits to the passed URL. The form has a submit buttonwith the value of thename.
<%=button_to"Sign in",sign_in_path%>would output the following HTML:
<formmethod="post"action="/sessions"class="button_to"><inputtype="submit"value="Sign in"/></form>See thebutton_to APIDocumentationfor more information.
3.2. current_page?
Returns true if the current request URL matches the givenoptions.
<%ifcurrent_page?(controller:'profiles',action:'show')%><strong>Currently on the profile page</strong><%end%>See thecurrent_page? APIDocumentationfor more information.
3.3. link_to
Links to a URL derived fromurl_for under the hood. It's commonly used tocreate links for RESTful resources, especially when passing models as argumentstolink_to.
link_to"Profile",@profile# => <a href="/profiles/1">Profile</a>link_to"Book",@book# given a composite primary key [:author_id, :id]# => <a href="/books/2_1">Book</a>link_to"Profiles",profiles_path# => <a href="/profiles">Profiles</a>link_tonil,"https://example.com"# => <a href="https://example.com">https://example.com</a>link_to"Articles",articles_path,id:"articles",class:"article__container"# => <a href="/articles">Articles</a>You can use a block if your link target can't fit in the name parameter.
<%=link_to@profiledo%><strong><%=@profile.name%></strong> --<span>Check it out!</span><%end%>It would output the following HTML:
<ahref="/profiles/1"><strong>David</strong> --<span>Check it out!</span></a>See thelink_to APIDocumentationfor more information.
3.4. mail_to
Generates amailto link tag to the specified email address. You can alsospecify the link text, additional HTML options, and whether to encode the emailaddress.
mail_to"john_doe@gmail.com"# => <a href="mailto:john_doe@gmail.com">john_doe@gmail.com</a>mail_to"me@john_doe.com",cc:"me@jane_doe.com",subject:"This is an example email"# => <a href="mailto:"me@john_doe.com?cc=me@jane_doe.com&subject=This%20is%20an%20example%20email">"me@john_doe.com</a>See themail_to APIDocumentationfor more information.
3.5. url_for
Returns the URL for the set ofoptions provided.
url_for@profile# => /profiles/1url_for[@hotel,@booking,page:2,line:3]# => /hotels/1/bookings/1?line=3&page=2url_for@post# given a composite primary key [:blog_id, :id]# => /posts/1_24. Sanitization
A set of methods for scrubbing text of undesired HTML elements. The helpers areparticularly useful for helping to ensure that only safe and valid HTML/CSS isrendered. It can also be useful to prevent XSS attacks by escaping or removingpotentially malicious content from user input before rendering it in your views.
This functionality is powered internally by therails-html-sanitizer gem.
4.1. sanitize
Thesanitize method will HTML encode all tags and strip all attributes thataren't specifically allowed.
sanitize@article.bodyIf either the:attributes or:tags options are passed, only the mentionedattributes and tags are allowed and nothing else.
sanitize@article.body,tags:%w(table tr td),attributes:%w(id class style)To change defaults for multiple uses, for example, adding table tags to thedefault:
# config/application.rbclassApplication<Rails::Applicationconfig.action_view.sanitized_allowed_tags=%w(table tr td)endSee thesanitize APIDocumentationfor more information.
4.2. sanitize_css
Sanitizes a block of CSS code, particularly when it comes across a styleattribute in HTML content.sanitize_css is particularly useful when dealingwith user-generated content or dynamic content that includes style attributes.
Thesanitize_css method below will remove the styles that are not allowed.
sanitize_css("background-color: red; color: white; font-size: 16px;")See thesanitize_css APIDocumentationfor more information.
4.3. strip_links
Strips all link tags from text leaving just the link text.
strip_links("<a href='https://rubyonrails.org'>Ruby on Rails</a>")# => Ruby on Railsstrip_links("emails to <a href='mailto:me@email.com'>me@email.com</a>.")# => emails to me@email.com.strip_links("Blog: <a href='http://myblog.com/'>Visit</a>.")# => Blog: Visit.See thestrip_links APIDocumentationfor more information.
4.4. strip_tags
Strips all HTML tags from the HTML, including comments and special characters.
strip_tags("Strip <i>these</i> tags!")# => Strip these tags!strip_tags("<b>Bold</b> no more! <a href='more.html'>See more</a>")# => Bold no more! See morestrip_links('<<a href="https://example.org">malformed & link</a>')# => <malformed & linkSee thestrip_tags APIDocumentationfor more information.
5. Assets
A set of methods for generating HTML that links views to assets such as images,JavaScript files, stylesheets, and feeds.
By default, Rails links to these assets on the current host in the publicfolder, but you can direct Rails to link to assets from a dedicated assetsserver by settingconfig.asset_host in the application configuration,typically inconfig/environments/production.rb.
For example, let's say your asset host isassets.example.com:
config.asset_host="assets.example.com"then the corresponding URL for animage_tag would be:
image_tag("rails.png")# => <img src="//assets.example.com/images/rails.png" />5.1. audio_tag
Generates an HTML audio tag with source(s), either as a single tag for a stringsource or nested source tags within an array for multiple sources. Thesourcescan be full paths, files in your public audios directory, orActive Storageattachments.
audio_tag("sound")# => <audio src="/audios/sound"></audio>audio_tag("sound.wav","sound.mid")# => <audio><source src="/audios/sound.wav" /><source src="/audios/sound.mid" /></audio>audio_tag("sound",controls:true)# => <audio controls="controls" src="/audios/sound"></audio>Internally,audio_tag usesaudio_path from theAssetUrlHelpersto build the audio path.
See theaudio_tag APIDocumentationfor more information.
5.2. auto_discovery_link_tag
Returns a link tag that browsers and feed readers can use to auto-detect an RSS,Atom, or JSON feed.
auto_discovery_link_tag(:rss,"http://www.example.com/feed.rss",{title:"RSS Feed"})# => <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed.rss" />See theauto_discovery_link_tag APIDocumentationfor more information.
5.3. favicon_link_tag
Returns a link tag for a favicon managed by the asset pipeline. Thesource canbe a full path or a file that exists in your assets directory.
favicon_link_tag# => <link href="/assets/favicon.ico" rel="icon" type="image/x-icon" />See thefavicon_link_tag APIDocumentationfor more information.
5.4. image_tag
Returns an HTML image tag for the source. Thesource can be a full path or afile that exists in yourapp/assets/images directory.
image_tag("icon.png")# => <img src="/assets/icon.png" />image_tag("icon.png",size:"16x10",alt:"Edit Article")# => <img src="/assets/icon.png" width="16" height="10" alt="Edit Article" />Internally,image_tag usesimage_path from theAssetUrlHelpersto build the image path.
See theimage_tag APIDocumentationfor more information.
5.5. javascript_include_tag
Returns an HTML script tag for each of the sources provided. You can pass in thefilename (.js extension is optional) of JavaScript files that exist in yourapp/assets/javascripts directory for inclusion into the current page, or youcan pass the full path relative to your document root.
javascript_include_tag("common")# => <script src="/assets/common.js"></script>javascript_include_tag("common",async:true)# => <script src="/assets/common.js" async="async"></script>Some of the most common attributes areasync anddefer, whereasync willallow the script to be loaded in parallel to be parsed and evaluated as soon aspossible, anddefer will indicate that the script is meant to be executedafter the document has been parsed.
Internally,javascript_include_tag usesjavascript_path from theAssetUrlHelpersto build the script path.
See thejavascript_include_tag APIDocumentationfor more information.
5.6. picture_tag
Returns an HTML picture tag for the source. It supports passing a String, anArray, or a Block.
picture_tag("icon.webp","icon.png")This generates the following HTML:
<picture><sourcesrcset="/assets/icon.webp"type="image/webp"/><sourcesrcset="/assets/icon.png"type="image/png"/><imgsrc="/assets/icon.png"/></picture>See thepicture_tag APIDocumentationfor more information.
5.7. preload_link_tag
Returns a link tag that browsers can use to preload the source. The source canbe the path of a resource managed by the asset pipeline, a full path, or a URI.
preload_link_tag("application.css")# => <link rel="preload" href="/assets/application.css" as="style" type="text/css" />See thepreload_link_tag APIDocumentationfor more information.
5.8. stylesheet_link_tag
Returns a stylesheet link tag for the sources specified as arguments. If youdon't specify an extension,.css will be appended automatically.
stylesheet_link_tag("application")# => <link href="/assets/application.css" rel="stylesheet" />stylesheet_link_tag("application",media:"all")# => <link href="/assets/application.css" media="all" rel="stylesheet" />media is used to specify the media type for the link. The most common mediatypes areall,screen,print, andspeech.
Internally,stylesheet_link_tag usesstylesheet_path from theAssetUrlHelpersto build the stylesheet path.
See thestylesheet_link_tag APIDocumentationfor more information.
5.9. video_tag
Generate an HTML video tag with source(s), either as a single tag for a stringsource or nested source tags within an array for multiple sources. Thesourcescan be full paths, files in your public videos directory, or Active Storageattachments.
video_tag("trailer")# => <video src="/videos/trailer"></video>video_tag(["trailer.ogg","trailer.flv"])# => <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>video_tag("trailer",controls:true)# => <video controls="controls" src="/videos/trailer"></video>Internally,video_tag usesvideo_path from theAssetUrlHelpersto build the video path.
See thevideo_tag APIDocumentationfor more information.
6. JavaScript
A set of methods for working with JavaScript in your views.
6.1. escape_javascript
Escapes carriage returns and single and double quotes for JavaScript segments.You would use this method to take a string of text and make sure that it doesn’tcontain any invalid characters when the browser tries to parse it.
For example, if you have a partial with a greeting that contains double quotes,you can escape the greeting to use in a JavaScript alert.
<%# app/views/users/greeting.html.erb %>My name is<%=current_user.name%>, and I'm here to say "Welcome to our website!"<script>vargreeting="<%=escape_javascriptrender('users/greeting')%>";alert(`Hello,${greeting}`);</script>This will escape the quotes correctly and display the greeting in an alert box.
See theescape_javascript APIDocumentationfor more information.
6.2. javascript_tag
Returns a JavaScript tag wrapping the provided code. You can pass a hash ofoptions to control the behavior of the<script> tag.
javascript_tag("alert('All is good')",type:"application/javascript")<scripttype="application/javascript">//<![CDATA[alert('All is good')//]]></script>Instead of passing the content as an argument, you can also use a block.
<%=javascript_tagtype:"application/javascript"do%> alert("Welcome to my app!")<%end%>See thejavascript_tag APIDocumentationfor more information.
7. Alternative Tags
A set of methods to generate HTML tags programmatically.
7.1. tag
Generates a standalone HTML tag with the givenname andoptions.
Every tag can be built with:
tag.some_tag_name(optionalcontent,options)where tag name can be e.g.br,div,section,article, or any tag really.
For example, here are some common uses:
tag.h1"All titles fit to print"# => <h1>All titles fit to print</h1>tag.div"Hello, world!"# => <div>Hello, world!</div>Additionally, you can pass options to add attributes to the generated tag.
tag.sectionclass:%w( kitties puppies )# => <section></section>In addition, HTMLdata-* attributes can be passed to thetag helper usingthedata option, with a hash containing key-value pairs of sub-attributes. Thesub-attributes are then converted todata-* attributes that are dasherized inorder to work well with JavaScript.
tag.divdata:{user_id:123}# => <div data-user-id="123"></div>See thetag APIDocumentationfor more information.
7.2. token_list
Returns a string of tokens built from the arguments provided. This method isalso aliased asclass_names.
token_list("cats","dogs")# => "cats dogs"token_list(nil,false,123,"","foo",{bar:true})# => "123 foo bar"mobile,alignment=true,"center"token_list("flex items-#{alignment}","flex-col":mobile)# => "flex items-center flex-col"class_names("flex items-#{alignment}","flex-col":mobile)# using the alias# => "flex items-center flex-col"8. Capture Blocks
A set of methods to let you extract generated markup which can be used in otherparts of a template or layout file.
It provides a method to capture blocks into variables throughcapture, and away to capture a block of markup for use in a layout throughcontent_for.
8.1. capture
Thecapture method allows you to extract part of a template into a variable.
<%@greeting=capturedo%><p>Welcome! The date and time is<%=Time.current%></p><%end%>You can then use this variable anywhere in your templates, layouts, or helpers.
<html><head><title>Welcome!</title></head><body><%=@greeting%></body></html>The return of capture is the string generated by the block.
@greeting# => "Welcome! The date and time is 2018-09-06 11:09:16 -0500"See thecapture APIDocumentationfor more information.
8.2. content_for
Callingcontent_for stores a block of markup in an identifier for later use.You can make subsequent calls to the stored content in other templates, helpermodules or the layout by passing the identifier as an argument toyield.
A common use case is to set the title of a page in acontent_for block.
You define acontent_for block in the special page's view, and then youyield it within the layout. For other pages, where thecontent_for blockisn't utilized, it remains empty, resulting in nothing being yielded.
<%# app/views/users/special_page.html.erb %><%content_for(:html_title){"Special Page Title"}%><%# app/views/layouts/application.html.erb %><html><head><title><%=content_for?(:html_title)?yield(:html_title):"Default Title"%></title></head></html>You'll notice that in the above example, we use thecontent_for? predicatemethod to conditionally render a title. This method checks whether any contenthas been captured yet usingcontent_for, enabling you to adjust parts of yourlayout based on the content within your views.
Additionally, you can employcontent_for within a helper module.
# app/helpers/title_helper.rbmoduleTitleHelperdefhtml_titlecontent_for(:html_title)||"Default Title"endendNow, you can callhtml_title in your layout to retrieve the content stored inthecontent_for block. If acontent_for block is set on the page beingrendered, such as in the case of thespecial_page, it will display the title.Otherwise, it will display the default text "Default Title".
content_for is ignored in caches. So you shouldn’t use it forelements that will be fragment cached.
You may be thinking what's the difference betweencapture andcontent_for?capture is used to capture a block of markup in a variable, whilecontent_for is used to store a block of markup in an identifier for later use.Internallycontent_for actually callscapture. However, the key differencelies in their behavior when invoked multiple times.content_for can be called repeatedly, concatenating the blocks it receives fora specific identifier in the order they are provided. Each subsequent callsimply adds to what's already stored. In contrast,capture only returns thecontent of the block, without keeping track of any previous invocations.
See thecontent_for APIDocumentationfor more information.
9. Performance
9.1. benchmark
Wrap abenchmark block around expensive operations or possible bottlenecks toget a time reading for the operation.
<%benchmark"Process data files"do%><%=expensive_files_operation%><%end%>This would add something likeProcess data files (0.34523) to the log, whichyou can then use to compare timings when optimizing your code.
This helper is a part of Active Support, and it is also available oncontrollers, helpers, models, etc.
See thebenchmark APIDocumentationfor more information.
9.2. cache
You can cache fragments of a view rather than an entire action or page. Thistechnique is useful for caching pieces like menus, lists of news topics, staticHTML fragments, and so on. It allows a fragment of view logic to be wrapped in acache block and served out of the cache store when the next request comes in.
Thecache method takes a block that contains the content you wish to cache.
For example, you could cache the footer of your application layout by wrappingit in acache block.
<%cachedo%><%=render"application/footer"%><%end%>You could also cache based on model instances, for example, you can cache eacharticle on a page by passing thearticle object to thecache method. Thiswould cache each article separately.
<%@articles.eachdo|article|%><%cachearticledo%><%=renderarticle%><%end%><%end%>When your application receives its first request to this page, Rails will writea new cache entry with a unique key. A key looks something like this:
views/articles/index:bea67108094918eeba32cd4a6f786301/articles/1SeeFragment Caching and thecache APIDocumentationfor more information.
10. Miscellaneous
10.1. atom_feed
Atom Feeds are XML-based file formats used to syndicate content and can be usedby users in feed readers to browse content or by search engines to help discoveradditional information about your site.
This helper makes building an Atom feed easy, and is mostly used in Buildertemplates for creating XML. Here's a full usage example:
# config/routes.rbresources:articles# app/controllers/articles_controller.rbdefindex@articles=Article.allrespond_todo|format|format.htmlformat.atomendend# app/views/articles/index.atom.builderatom_feeddo|feed|feed.title("Articles Index")feed.updated(@articles.first.created_at)@articles.eachdo|article|feed.entry(article)do|entry|entry.title(article.title)entry.content(article.body,type:"html")entry.authordo|author|author.name(article.author_name)endendendendSee theatom_feed APIDocumentationfor more information.
10.2. debug
Returns a YAML representation of an object wrapped with apre tag. Thiscreates a very readable way to inspect an object.
my_hash={"first"=>1,"second"=>"two","third"=>[1,2,3]}debug(my_hash)<preclass="debug_dump">---first: 1second: twothird:- 1- 2- 3</pre>See thedebug APIDocumentationfor more information.