Action View layout

Action View

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. - Martin Fowler

In this chapter we will enter in the architecture of MVC View, which provides the interface to the user, do interact with our apps.

ActionView View Rails the name of the component, and is provided to the user's file, we will use Template templates to present. This chapter assumes that readers will have a basic understanding of HTML.

Template model

What is the Template model? We know the server end provides the browser type is the HTML file, and the Template model is dynamically generated HTML method.

Comparatively speaking, we use static HTML address does not pass through the program generated HTM file

The Rails default used to generate the Template way is Embedded Ruby (ERb), if you have used PHP, JSP or ASP, then you will be very familiar with the wind the embedded code; this is a method, the most intuitive and easy to learn. For example, the following is a short embedded in present time ERb, middle <=%> part is Ruby code:

<h1><%= %></h1>

Rails Template file location and name is a mystery, for example app/views/welcome/index.html.erb, welcome directory is its Controller name, file the first section of index is its Action name, the attached file name is used to specify what way to produce what &# 26684; type of file: index.html.erb produced by ERb HTML type file. Why have such practices, you may have guessed, is the use of ERb does not necessarily mean is used to generate the HTML. What the Template engine (Rails also known as Template Handler) files, and files Format type two. So ERb actually can be used to produce any text file type, such as CSV, XML, JavaScript etc.

Although it can be, but the best way to ERb is not usually in the XML, we will use Builder to generate XML, such as a show.xml.builder file:

people do |p|
  p.person "test"

Will have the following XML:


The following is a template engine with common; combination:

Type Engine
html, xhtml erb
js erb
xml, rss, atom builder

The extension of Template Handler

Rails by default only built in ERb and Builder of the two sets of model engine, but to expand very easily. For example, in the Rails community, is also very popular with the set of HAML template engine to replace the ERb. HAML is a set of simplified HTML write using indentation technique; type, for example:


Will have the following HTML:

<div id="content">
  <div class="box">

To install and use, only need to add a gem Gemfile files " haml-rails" and bundle install. But compared to the ERb, the use of HAML can be more efficient to write HTML model, but will need to consider the team in the Webpage designers are able to use.

The use of Renderer in Controller directly return results

There are some type actually don't need Template engine, only need to direct render to Controller and the results can be, for example JSON and CSV or XML. Rails provides the to_xml and to_json methods on the ActiveRecord model. While CSV can use the FasterCSV library. Examples are as follows:

require 'csv'
class PeopleController <ApplicationController

def index
    @people = Person.all
    respond_to do |format|
      format.json{ render :json => @person.to_json }
      format.xml { render :xml => @person.to_xml }
      format.csv do
        csv_string = CSV.generate do |csv|
            csv <<["Name", "Created At"]
            @people.each do |person|
                csv <<[, person.created_at]
        render :text => csv_string

Ruby 1.8.7 you need to specify gem " in the Gemfile; fastercsv", CSV into FasterCSV.

ERb tag

In addition to the introduction of the ERb tag <%;%> will output the intermediate Ruby program execution results, there are some other usage:

<% %>

So it will not output any results, typically used in the if or the loop condition, for example:

<% @people.each do |person| %>
    <% if %>
        <p><%= %></p>
    <% end %>
<% end %>

The above <%%> tag does not output HTML content, but in the original HTML code line, in order to avoid excess output line, can use <%--%>. But in fact not many people care about is, after all, this does not affect the user's page.

<%# blah blah %>

This is a comment, not output any content. But if you need the whole multi line comment, often wrote:

<%- output = false -%>
<% if output %>
    <%= foo %>
    <%= bar %>
<% end %>

At this time as long as the control of output value is the output switch, later we will be output into a Helper method, the output so that it can be decided whether the dynamic content.

Layout version

Layout can be used to wrap the Template model, so that different View can share Layout as the file of the head and tail. So we can build version of shared pages for the station. This file is the default app/views/layouts/application.html.erb. If the directory in the app/views/layouts with a Controller Layout file, all of the Views that the Controller will use the same Layout.

The default Layout looks as follows:

<!DOCTYPE html>
  <%= stylesheet_link_tag    "application" %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>

<%= yield %>


The <%> = yield; will be replaced with individual Action model.

At the beginning of the <DOCTYPE html>!; that this is a HTML5 file, this declaration method downward compatibility in all HTML4 browser.

If you need to specify the Controller of the Layout, may do so:

class EventsController <ApplicationController
   layout "special"

This will specify the Events Controller Views app/views/layouts/special.html.erb the Layout, you can add parameters: only or except: that only a specific Action:

class EventsController <ApplicationController
   layout "special", :only => :index


class EventsController <ApplicationController
   layout "special", :except => [:show, :edit, :new]

Please pay attention to the use of string and Symbol is different. Using Symbol, it would be to dynamically decide through a method of the same name, such as the following Layout is determined by the determine_layout method:

class EventsController <ApplicationController
   layout :determine_layout


	def determine_layout
   	   ( rand(100)%2 == 0 )? "event_open" : "event_closed"

In addition to set up Layout in Controller level, we can also set the individual Action use a different Layout, for example:

def show
   @event = Event.find(params[:id])
	render :layout => "foobar"

So show Action will apply foobar Layout model. The more common case is to turn off the Layout, then we can write: layout render => false.

Custom Layout content

In addition to the <yield%> = Template; will load content, we can pre self some other block can be placed for Template content. For example, to put a side bar used in Layout block, named: sidebar:

<div id="sidebar">
    <%= yield :sidebar %>
<div id="content">
    <%= yield %>

Then the Template model, any place:

<%= content_for :sidebar do %>
<% end %>

Then the content will be put into the Layout <sidebar%> yield:%.

Successor to the Layout version of the (Advanced)

Partial model Partials

The local model can be Template duplicate code out, for example, add and edit our demonstration in the Part1 of the form. Partial Template naming convention is the bottom line at the beginning, but without the bottom line call, for example:

<%= render :partial => "common/nav" %>

This will use the app/views/common/_nav.html.erb template. If you use the Partial model and the directory where Partial is the same, can omit the first section of the common path.

In the Partial model is able to directly use the instance variables (i.e. variables @ at the beginning). But the practice is good through: locals express the locals, this program will be more clearly, the Partial model is easy to be used repeatedly:

<%= render :partial => "common/nav", :locals => { :a => 1, :b => 2 } %>

In the partial model, you can access to the local variables A and B.

If the array data, the general intuition would write something like this:

@items.each do |item|
  render :partial => "item", :locals => { :item => item }

However, partial can support the processing array:

render :partial => "item", :collection => @items, :as => :item

This benefits not only less typing only, also can benefit, Rails will do the best for this form.

The collection type Collection

Like tr or Li that would have been repeating Template elements, we can use the collection parameter to Rails, the collection type Partial optimal efficiency, such as the following program:

    <% @people.each do |person| %>
        <%= render :partial => "person", :locals => { :person => person } %>
    <% end %>

Can be changed using the Collection method,

    <%= render :partial => "person", :collection => @people %>

So can lose two lines of each code, execution efficiency and better.

Posted by Ella at December 20, 2013 - 8:14 AM