**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.** Action View Overview ==================== After reading this guide, you will know: * What Action View is and how to use it with Rails. * How best to use templates, partials, and layouts. * What helpers are provided by Action View. * How to use localized views. -------------------------------------------------------------------------------- What is Action View? -------------------- In Rails, web requests are handled by [Action Controller](action_controller_overview.html) and Action View. Typically, Action Controller is concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response. Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves. NOTE: Some features of Action View are tied to Active Record, but that doesn't mean Action View depends on Active Record. Action View is an independent package that can be used with any sort of Ruby libraries. Using Action View with Rails ---------------------------- For each controller there is an associated directory in the `app/views` directory which holds the template files that make up the views associated with that controller. These files are used to display the view that results from each controller action. Let's take a look at what Rails does by default when creating a new resource using the scaffold generator: ```bash $ bin/rails generate scaffold article [...] invoke scaffold_controller create app/controllers/articles_controller.rb invoke erb create app/views/articles create app/views/articles/index.html.erb create app/views/articles/edit.html.erb create app/views/articles/show.html.erb create app/views/articles/new.html.erb create app/views/articles/_form.html.erb [...] ``` There is a naming convention for views in Rails. Typically, the views share their name with the associated controller action, as you can see above. For example, the index controller action of the `articles_controller.rb` will use the `index.html.erb` view file in the `app/views/articles` directory. The complete HTML returned to the client is composed of a combination of this ERB file, a layout template that wraps it, and all the partials that the view may reference. Within this guide you will find more detailed documentation about each of these three components. Templates, Partials, and Layouts ------------------------------- As mentioned, the final HTML output is a composition of three Rails elements: `Templates`, `Partials` and `Layouts`. Below is a brief overview of each of them. ### Templates Action View templates can be written in several ways. If the template file has a `.erb` extension then it uses a mixture of ERB (Embedded Ruby) and HTML. If the template file has a `.builder` extension then the `Builder::XmlMarkup` library is used. Rails supports multiple template systems and uses a file extension to distinguish amongst them. For example, an HTML file using the ERB template system will have `.html.erb` as a file extension. #### ERB Within an ERB template, Ruby code can be included using both `<% %>` and `<%= %>` tags. The `<% %>` tags are used to execute Ruby code that does not return anything, such as conditions, loops, or blocks, and the `<%= %>` tags are used when you want output. Consider the following loop for names: ```html+erb
A product of Danish Design during the Winter of '79...
Here are a few of our fine products:
<% @products.each do |product| %> <%= render partial: "product", locals: { product: product } %> <% end %> <%= render "shared/footer" %> ``` Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page. #### `render` without `partial` and `locals` options In the above example, `render` takes 2 options: `partial` and `locals`. But if these are the only options you want to pass, you can skip using these options. For example, instead of: ```erb <%= render partial: "product", locals: { product: @product } %> ``` You can also do: ```erb <%= render "product", product: @product %> ``` #### The `as` and `object` options By default `ActionView::Partials::PartialRenderer` has its object in a local variable with the same name as the template. So, given: ```erb <%= render partial: "product" %> ``` within `_product` partial we'll get `@product` in the local variable `product`, as if we had written: ```erb <%= render partial: "product", locals: { product: @product } %> ``` The `object` option can be used to directly specify which object is rendered into the partial; useful when the template's object is elsewhere (e.g. in a different instance variable or in a local variable). For example, instead of: ```erb <%= render partial: "product", locals: { product: @item } %> ``` we would do: ```erb <%= render partial: "product", object: @item %> ``` With the `as` option we can specify a different name for the said local variable. For example, if we wanted it to be `item` instead of `product` we would do: ```erb <%= render partial: "product", object: @item, as: "item" %> ``` This is equivalent to ```erb <%= render partial: "product", locals: { item: @item } %> ``` #### Rendering Collections It is very common that a template will need to iterate over a collection and render a sub-template for each of the elements. This pattern has been implemented as a single method that accepts an array and renders a partial for each one of the elements in the array. So this example for rendering all the products: ```erb <% @products.each do |product| %> <%= render partial: "product", locals: { product: product } %> <% end %> ``` can be rewritten in a single line: ```erb <%= render partial: "product", collection: @products %> ``` When a partial is called with a collection, the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is `_product`, and within it you can refer to `product` to get the collection member that is being rendered. You can use a shorthand syntax for rendering collections. Assuming `@products` is a collection of `Product` instances, you can simply write the following to produce the same result: ```erb <%= render @products %> ``` Rails determines the name of the partial to use by looking at the model name in the collection, `Product` in this case. In fact, you can even render a collection made up of instances of different models using this shorthand, and Rails will choose the proper partial for each member of the collection. #### Spacer Templates You can also specify a second partial to be rendered between instances of the main partial by using the `:spacer_template` option: ```erb <%= render partial: @products, spacer_template: "product_ruler" %> ``` Rails will render the `_product_ruler` partial (with no data passed to it) between each pair of `_product` partials. ### Layouts Layouts can be used to render a common view template around the results of Rails controller actions. Typically, a Rails application will have a couple of layouts that pages will be rendered within. For example, a site might have one layout for a logged in user and another for the marketing or sales side of the site. The logged in user layout might include top-level navigation that should be present across many controller actions. The sales layout for a SaaS app might include top-level navigation for things like "Pricing" and "Contact Us" pages. You would expect each layout to have a different look and feel. You can read about layouts in more detail in the [Layouts and Rendering in Rails](layouts_and_rendering.html) guide. Partial Layouts --------------- Partials can have their own layouts applied to them. These layouts are different from those applied to a controller action, but they work in a similar fashion. Let's say we're displaying an article on a page which should be wrapped in a `div` for display purposes. Firstly, we'll create a new `Article`: ```ruby Article.create(body: 'Partial Layouts are cool!') ``` In the `show` template, we'll render the `_article` partial wrapped in the `box` layout: **articles/show.html.erb** ```erb <%= render partial: 'article', layout: 'box', locals: { article: @article } %> ``` The `box` layout simply wraps the `_article` partial in a `div`: **articles/_box.html.erb** ```html+erb<%= article.body %>
Welcome! The date and time is <%= Time.now %>
<% end %> ``` The captured variable can then be used anywhere else. ```html+erbWelcome! The date and time is <%= Time.now %>
``` **app/views/articles/special.html.erb** ```html+erbThis is a special page.
<% content_for :special_script do %> <% end %> ``` ### DateHelper #### date_select Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute. ```ruby date_select("article", "published_on") ``` #### datetime_select Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute. ```ruby datetime_select("article", "published_on") ``` #### distance_of_time_in_words Reports the approximate distance in time between two Time or Date objects or integers as seconds. Set `include_seconds` to true if you want more detailed approximations. ```ruby distance_of_time_in_words(Time.now, Time.now + 15.seconds) # => less than a minute distance_of_time_in_words(Time.now, Time.now + 15.seconds, include_seconds: true) # => less than 20 seconds ``` #### select_date Returns a set of HTML select-tags (one for year, month, and day) pre-selected with the `date` provided. ```ruby # Generates a date select that defaults to the date provided (six days after today) select_date(Time.today + 6.days) # Generates a date select that defaults to today (no specified date) select_date() ``` #### select_datetime Returns a set of HTML select-tags (one for year, month, day, hour, and minute) pre-selected with the `datetime` provided. ```ruby # Generates a datetime select that defaults to the datetime provided (four days after today) select_datetime(Time.now + 4.days) # Generates a datetime select that defaults to today (no specified datetime) select_datetime() ``` #### select_day Returns a select tag with options for each of the days 1 through 31 with the current day selected. ```ruby # Generates a select field for days that defaults to the day for the date provided select_day(Time.today + 2.days) # Generates a select field for days that defaults to the number given select_day(5) ``` #### select_hour Returns a select tag with options for each of the hours 0 through 23 with the current hour selected. ```ruby # Generates a select field for hours that defaults to the hours for the time provided select_hour(Time.now + 6.hours) ``` #### select_minute Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected. ```ruby # Generates a select field for minutes that defaults to the minutes for the time provided. select_minute(Time.now + 10.minutes) ``` #### select_month Returns a select tag with options for each of the months January through December with the current month selected. ```ruby # Generates a select field for months that defaults to the current month select_month(Date.today) ``` #### select_second Returns a select tag with options for each of the seconds 0 through 59 with the current second selected. ```ruby # Generates a select field for seconds that defaults to the seconds for the time provided select_second(Time.now + 16.seconds) ``` #### select_time Returns a set of HTML select-tags (one for hour and minute). ```ruby # Generates a time select that defaults to the time provided select_time(Time.now) ``` #### select_year Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius can be changed using the `:start_year` and `:end_year` keys in the `options`. ```ruby # Generates a select field for five years on either side of Date.today that defaults to the current year select_year(Date.today) # Generates a select field from 1900 to 2009 that defaults to the current year select_year(Date.today, start_year: 1900, end_year: 2009) ``` #### time_ago_in_words Like `distance_of_time_in_words`, but where `to_time` is fixed to `Time.now`. ```ruby time_ago_in_words(3.minutes.from_now) # => 3 minutes ``` #### time_select Returns a set of select tags (one for hour, minute, and optionally second) pre-selected for accessing a specified time-based attribute. The selects are prepared for multi-parameter assignment to an Active Record object. ```ruby # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute time_select("order", "submitted") ``` ### DebugHelper Returns a `pre` tag that has object dumped by YAML. This creates a very readable way to inspect an object. ```ruby my_hash = { 'first' => 1, 'second' => 'two', 'third' => [1,2,3] } debug(my_hash) ``` ```html--- first: 1 second: two third: - 1 - 2 - 3``` ### FormHelper Form helpers are designed to make working with models much easier compared to using just standard HTML elements by providing a set of methods for creating forms based on your models. This helper generates the HTML for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed back to the controller. There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that don't work with model attributes, check the `ActionView::Helpers::FormTagHelper` documentation. The core method of this helper, `form_with`, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it: ```html+erb <%= form_with model: @person do |form| %> <%= form.text_field :first_name %> <%= form.text_field :last_name %> <%= submit_tag 'Create' %> <% end %> ``` The HTML generated for this would be: ```html ``` The params object created when this form is submitted would look like: ```ruby {"utf8" => "✓", "authenticity_token" => "lTuvBzs7ANygT0NFinXj98tfw3Emfm65wwYLbUvoWsK2pngccIQSUorM2C035M9dZswXgWTvKwFS8W5TVblpYw==", "person" => {"first_name" => "William", "last_name" => "Smith"}, "commit" => "Create", "controller" => "people", "action" => "create"} ``` The params hash has a nested person value, which can therefore be accessed with `params[:person]` in the controller. #### check_box Returns a checkbox tag tailored for accessing a specified attribute. ```ruby # Let's say that @article.validated? is 1: check_box("article", "validated") # => # ``` #### fields_for Creates a scope around a specific model object. This makes `fields_for` suitable for specifying additional model objects in the same form: ```html+erb <%= form_with model: @person do |person_form| %> First name: <%= person_form.text_field :first_name %> Last name : <%= person_form.text_field :last_name %> <%= fields_for @person.permission do |permission_fields| %> Admin? : <%= permission_fields.check_box :admin %> <% end %> <% end %> ``` #### file_field Returns a file upload input tag tailored for accessing a specified attribute. ```ruby file_field(:user, :avatar) # => ``` #### form_with Creates a form builder to work with. If a `model` argument is specified, form fields will be scoped to that model, and form field values will be prepopulated with corresponding model attributes. ```html+erb <%= form_with model: @article do |form| %> <%= form.label :title, 'Title' %>: <%= form.text_field :title %>
<%= text_field_tag 'name' %>
<% end %> # => ``` #### file_field_tag Creates a file upload field. ```html+erb <%= form_with url: new_account_avatar_path(@account), multipart: true do %> <%= file_field_tag 'avatar' %> <%= submit_tag %> <% end %> ``` Example output: ```ruby file_field_tag 'attachment' # => ``` #### hidden_field_tag Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or data that should be hidden from the user. ```ruby hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@' # => ``` #### image_submit_tag Displays an image which when clicked will submit the form. ```ruby image_submit_tag("login.png") # => ``` #### label_tag Creates a label field. ```ruby label_tag 'name' # => ``` #### password_field_tag Creates a password field, a masked text field that will hide the users input behind a mask character. ```ruby password_field_tag 'pass' # => ``` #### radio_button_tag Creates a radio button; use groups of radio buttons named the same to allow users to select from a group of options. ```ruby radio_button_tag 'favorite_color', 'maroon' # => ``` #### select_tag Creates a dropdown selection box. ```ruby select_tag "people", "" # => ``` #### submit_tag Creates a submit button with the text provided as the caption. ```ruby submit_tag "Publish this article" # => ``` #### text_area_tag Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions. ```ruby text_area_tag 'article' # => ``` #### text_field_tag Creates a standard text field; use these text fields to input smaller chunks of text like a username or a search query. ```ruby text_field_tag 'name' # => ``` #### email_field_tag Creates a standard input field of email type. ```ruby email_field_tag 'email' # => ``` #### url_field_tag Creates a standard input field of url type. ```ruby url_field_tag 'url' # => ``` #### date_field_tag Creates a standard input field of date type. ```ruby date_field_tag "dob" # => ``` ### JavaScriptHelper Provides functionality for working with JavaScript in your views. #### escape_javascript Escape carrier returns and single and double quotes for JavaScript segments. #### javascript_tag Returns a JavaScript tag wrapping the provided code. ```ruby javascript_tag "alert('All is good')" ``` ```html ``` ### NumberHelper Provides methods for converting numbers into formatted strings. Methods are provided for phone numbers, currency, percentage, precision, positional notation, and file size. #### number_to_currency Formats a number into a currency string (e.g., $13.65). ```ruby number_to_currency(1234567890.50) # => $1,234,567,890.50 ``` #### number_to_human_size Formats the bytes in size into a more understandable representation; useful for reporting file sizes to users. ```ruby number_to_human_size(1234) # => 1.2 KB number_to_human_size(1234567) # => 1.2 MB ``` #### number_to_percentage Formats a number as a percentage string. ```ruby number_to_percentage(100, precision: 0) # => 100% ``` #### number_to_phone Formats a number into a phone number (US by default). ```ruby number_to_phone(1235551234) # => 123-555-1234 ``` #### number_with_delimiter Formats a number with grouped thousands using a delimiter. ```ruby number_with_delimiter(12345678) # => 12,345,678 ``` #### number_with_precision Formats a number with the specified level of `precision`, which defaults to 3. ```ruby number_with_precision(111.2345) # => 111.235 number_with_precision(111.2345, precision: 2) # => 111.23 ``` ### SanitizeHelper The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements. #### sanitize This sanitize helper will HTML encode all tags and strip all attributes that aren't specifically allowed. ```ruby sanitize @article.body ``` If either the `:attributes` or `:tags` options are passed, only the mentioned attributes and tags are allowed and nothing else. ```ruby 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 the default: ```ruby class Application < Rails::Application config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td' end ``` #### sanitize_css(style) Sanitizes a block of CSS code. #### strip_links(html) Strips all link tags from text leaving just the link text. ```ruby strip_links('Ruby on Rails') # => Ruby on Rails ``` ```ruby strip_links('emails to me@email.com.') # => emails to me@email.com. ``` ```ruby strip_links('Blog: Visit.') # => Blog: Visit. ``` #### strip_tags(html) Strips all HTML tags from the html, including comments. This functionality is powered by the rails-html-sanitizer gem. ```ruby strip_tags("Strip these tags!") # => Strip these tags! ``` ```ruby strip_tags("Bold no more! See more") # => Bold no more! See more ``` NB: The output may still contain unescaped '<', '>', '&' characters and confuse browsers. ### UrlHelper Provides methods to make links and get URLs that depend on the routing subsystem. #### url_for Returns the URL for the set of `options` provided. ##### Examples ```ruby url_for @profile # => /profiles/1 url_for [ @hotel, @booking, page: 2, line: 3 ] # => /hotels/1/bookings/1?line=3&page=2 ``` #### link_to Links to a URL derived from `url_for` under the hood. Primarily used to create RESTful resource links, which for this example, boils down to when passing models to `link_to`. **Examples** ```ruby link_to "Profile", @profile # => Profile ``` You can use a block as well if your link target can't fit in the name parameter. ERB example: ```html+erb <%= link_to @profile do %> <%= @profile.name %> -- Check it out! <% end %> ``` would output: ```html David -- Check it out! ``` See [the API Doc for more info](https://api.rubyonrails.org/v6.0/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to) #### button_to Generates a form that submits to the passed URL. The form has a submit button with the value of the `name`. ##### Examples ```html+erb <%= button_to "Sign in", sign_in_path %> ``` would roughly output something like: ```html ``` See [the API Doc for more info](https://api.rubyonrails.org/v6.0/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to) ### CsrfHelper Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site request forgery protection parameter and token, respectively. ```html <%= csrf_meta_tags %> ``` NOTE: Regular forms generate hidden fields so they do not use these tags. More details can be found in the [Rails Security Guide](security.html#cross-site-request-forgery-csrf). Localized Views --------------- Action View has the ability to render different templates depending on the current locale. For example, suppose you have an `ArticlesController` with a show action. By default, calling this action will render `app/views/articles/show.html.erb`. But if you set `I18n.locale = :de`, then `app/views/articles/show.de.html.erb` will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available. You can use the same technique to localize the rescue files in your public directory. For example, setting `I18n.locale = :de` and creating `public/500.de.html` and `public/404.de.html` would allow you to have localized rescue pages. Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to `app/controllers/application.rb`: ```ruby before_action :set_expert_locale def set_expert_locale I18n.locale = :expert if current_user.expert? end ``` Then you could create special views like `app/views/articles/show.expert.html.erb` that would only be displayed to expert users. You can read more about the Rails Internationalization (I18n) API [here](i18n.html).