Rails Views – (Part I)



Rails Views – (Part I)

0 0


rails_views_part1_presentation


On Github vlasiak / rails_views_part1_presentation

Rails Views

(Part I)

Quick lecture overview

  • Why do we need views?
  • Views rendering
  • Templates, Partials and Layouts
  • Some Action View helpers overview
  • FormHelper
  • FormTagHelper

Why do we need views?

In the Model-View-Controller (MVC) pattern, views are intended exclusively for encapsulating presentation logic. They should not contain any application logic or database retrieval code. All application logic should be handled by the controller. A view renders the appropriate UI by using the data that is passed to it from the controller.

Views rendering

Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes.

Another way

There are a variety of ways to customize the behavior of render. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML.

def update
  @product = Product.find(params[:id])
  if @product.update(product_params)
    redirect_to(@product)
  else
    render 'edit'
  end
end
					

Examples

render nothing: true #rendering nothing
render 'products/show' #rendering from another controller
render template: 'products/show' #actually the same
render "/u/apps/warehouse_app/current/app/views/products/show" #rendering from another file
render file: "/u/apps/warehouse_app/current/app/views/products/show" #actually the same
render inline: "<% products.each do |p| %><p><%= p.name %></p><% end %>" #rendering ERB directly
render html: "<span>Success</span>".html_safe #rendering HTML directly
render plain: 'OK' #rendering text
render json: @product #rendering JSON
render xml: @product #rendering XML
render js: "alert('Hello Rails');" #rendering JS
					

ERB explanation

ERB (Embedded RuBy) is a feature of Ruby that enables you to conveniently generate any kind of text, in any quantity, from templates. The templates themselves combine plain text with Ruby code for variable substitution and flow control, which makes them easy to write and maintain.

Hello, <%= @name %>.
Today is <%= Time.now.strftime('%A') %>.

 <% for @item in @shopping_list %>
   <%= @item %>
 <% end %>
					

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.

Templates, Partials and Layouts

As mentioned, the final HTML output is a composition of three Rails elements: Templates, Partials and Layouts.

Templates

<%= form_for(@product) do |f| %>
  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :price %><br>
    <%= f.number_field :price %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
					

Partials

Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With partials, you can extract pieces of code from your templates to separate files and also reuse them throughout your templates.

<%= render "shared/menu" %>
					

That code will pull in the partial from app/views/shared/_menu.html.erb. Sharing variables between partials:

<%= render partial: "product", locals: {product: @product} %>
<%= render partial: "product", as: "item" %>
					

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.

articles/show.html.erb
<%= render partial: 'article', layout: 'box', locals: {article: @article} %>

#articles/_box.html.erb
<div class="box">
  <%= yield %>
</div>
					
More about layouts

Some Action View helpers overview

Rails Guide (Helpers)

FormHelper

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

# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
<%= form_for @person, url: {action: "create"} do |f| %>
  <%= f.text_field :first_name %>
  <%= f.text_field :last_name %>
  <%= submit_tag 'Create' %>
<% end %>
					

The HTML generated for this would be:

<form action="/people/create" method="post">
  <input id="person_first_name" name="person[first_name]" type="text">
  <input id="person_last_name" name="person[last_name]" type="text">
  <input name="commit" type="submit" value="Create">
</form>
					

FormTagHelper

Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like FormHelper does. Instead, you provide the names and values manually.

Rails Guide (FormHelper)
<%= form_tag '/articles' do %>
  <div><%= submit_tag 'Save' %></div>
<% end %>
# => <form action="/articles" method="post"><div><input type="submit" name="submit" value="Save"></div></form>

check_box_tag 'accept'
# => <input id="accept" name="accept" type="checkbox" value="1">

<%= form_tag({action:"post"}, multipart: true) do %>
  <label for="file">File to Upload</label> <%= file_field_tag "file" %>
  <%= submit_tag %>
<% end %>

hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
# => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@">

label_tag 'name'
# => <label for="name">Name</label>

password_field_tag 'pass'
# => <input id="pass" name="pass" type="password">

radio_button_tag 'gender', 'male'
# => <input id="gender_male" name="gender" type="radio" value="male">

select_tag "people", "<option>David</option>"
# => <select id="people" name="people"><option>David</option></select>

text_area_tag 'article'
# => <textarea id="article" name="article"></textarea>

text_field_tag 'name'
# => <input id="name" name="name" type="text">
					
No questions? No answers!

Created by Vasyl Lasiak / @vlasiak

1
Rails Views (Part I)