Ruby on Rails[c] Up and Running

5.6. Views

5.6.1. View Templates

All view templates are stored in app/views /controllername . The extension determines what kind of template it is:

*. rhtml

Ruby HTML (using ERB)

*.rxml

Ruby XML (using Builder)

*.rjs

Ruby JavaScript

All instance variables of the controller are available to the view. In addition, the following special objects can be accessed:

headers

The headers of the outgoing response

request

The incoming request object

response

The outgoing response object

params

The parameter hash

session

The session hash

controller

The current controller

5.6.2. RHTML

RHTML is HTML mixed with Ruby, using tags. All of Ruby is available for programming:

<% %> # executes the Ruby code <%= %> # executes the Ruby code and displays the result <ul> <% @products.each do p %> <li><%= h @p.name %></li> <% end %> </ul>

The output of anything in <%= %> tags is directly copied to the HTML output stream. To secure against HTML injection, use the h( ) function to HTML-escape the output. For example:

<%=h @user_entered_notes %>

5.6.3. RXML

Creates XML files:

xml.instruct! # <?xml version="1.0" encoding="UTF-8"?> xml.comment! "a comment" # <!-- a comment --> xml.feed "xmlns" => "http://www.w3.org/2005/Atom" do xml.title "My Atom Feed" xml.subtitle h(@feed.subtitle), "type" => 'html' xml.link url_for( :only_path => false, :controller => 'feed', :action => 'atom' ) xml.updated @updated.iso8601 xml.author do xml.name "Jens-Christian Fischer" xml.email "jcfischer@gmail.com" end @entries.each do entry xml.entry do xml.title entry.title xml.link "href" => url_for ( :only_path => false, :controller => 'entries', :action => 'show', :id => entry ) xml.id entry.urn xml.updated entry.updated.iso8601 xml.summary h(entry.summary) end end end

Learn more: http:// rubyforge .org/projects/builder/.

5.6.4. RJS

In addition to HTML and XML templates, Rails also understands JavaScript templates. They allow you to easily create complex alterations of the displayed page. You can manipulate a page element with the following methods :

select

Select a DOM element for further processing:

page.select('pattern') # selects an item on the page through a CSS pattern # select('p'), select('p.welcome b') page.select('div.header em').first.hide page.select('#items li').eacj do value value.hide end

insert_html

Inserts content into the DOM at a specific position:

page.insert_html :position, id, content

position can be one of the following:

:top :bottom :before :after

replace_html

Replaces the inner HTML of the specified DOM element:

page.replace_html 'title', "This is the new title" page.replace_html 'person-45', :partial => 'person', :object => @person

replace

Replaces the outer HTML (i.e., the entire element) of the specified DOM element:

page.replace 'task', :partial => 'task', :object => @task

remove

Removes the specified DOM element:

page.remove 'edit-button'

hide

Hides the specified DOM element:

page.hide 'some-element'

show

Shows the specified DOM element:

page.show 'some-element'

toggle

Toggles the visibility of a DOM element:

page.toggle 'some-element'

alert

Displays an alert box:

page.alert 'Hello world'

redirect_to

Redirects the browser to a given location:

page.redirect_to :controller => 'blog', :action => 'show', :id => @post

call

Calls another JavaScript function:

page.call foo, 1, 2

assign

Assigns a value to a JavaScript variable:

page.assign "foo", 42

<<

Writes raw JavaScript to the page:

page << "alert('hello world);"

delay

Delays the code in the block by a number of seconds:

page.delay(10) do page.visual_effect :fade, 'notice' end

visual_effect

Calls a Scriptaculous effect:

page.visual_effect :highlight, 'notice', :duration => 2

sortable

Creates a sortable element:

page.sortable 'my_list', :url => { :action => 'order' }

dragable

Creates a draggable element:

page.dragable 'my_image', :revert => true

drop_receiving

Creates an element for receiving drops :

page.drop_recieving 'my_cart', :url => { :controller => 'cart', :action => 'add' }

Learn more: http://api.rubyonrails.com/classes/ActionView/Base.html.

5.6.5. Helpers

Small functions, normally used for displaying data, can be extracted to helpers. Each view has its own helper class (in app/helpers ). Common functionality is stored in app/helpers/application_helper.rb .

5.6.6. Links

link_to "Name", :controller => 'post', :action => 'show', :id => @post.id link_to "Delete", { :controller => "admin", :action => "delete", :id => @post }, { :class => 'css-class', :id => 'css-id', :confirm => "Are you sure?" } image_tag "spinner.png", :class => "image", :alt => "Spinner" mail_to "info@invisible.ch", "send mail", :subject => "Support request by #{@user.name}", :cc => @user.email, :body => '....', :encoding => "javascript" stylesheet_link_tag "scaffold", "admin", :media => "all"

Learn more: http://api.rubyonrails.com/classes/ActionView/Helpers/UrlHelper.html.

5.6.7. HTML Forms

5.6.7.1. Form

<%= form_tag { :action => :save }, { :method => :post } %>

This creates a form tag with the specified action, and makes it a POST request.

Use :multipart => true to define a MIME-multipart form (for file uploads).

5.6.7.2. Text Fields

<%= text_field :modelname, :attribute_name, options %>

The following creates a text input field of the form:

<input type="text" name="modelname[attribute_name]" id="attributename" />

Example:

text_field "post", "title", "size" => 20 <input type="text" id="post_title" name="post[title]" size="20" value="#{@post.title}" />

Create a hidden field:

<%= hidden_field ... %>

Create a password field (all input shown as stars):

<%= password_field ... %>

Create a file field:

<%= file_field ... %>

5.6.7.3. Text Area

<%= text_area ... %>

This example:

text_area "post", "body", "cols" => 20, "rows" => 40

generates:

<textarea cols="20" rows="40" id="post_body" name="post[body]"> #{@post.body} </textarea>

5.6.7.4. Radio Button

<%= radio_button :modelname, :attribute, :tag_value, options %>

Example:

radio_button "post", "category", "rails" radio_button "post", "category", "java" <input type="radio" id="post_category" name="post[category]" value="rails" checked="checked" /> <input type="radio" id="post_category" name="post[category]" value="java" />

5.6.7.5. Checkbox

<%= check_box :modelname, :attribute, options, on_value, off_value %>

Example:

check_box "post", "validated" # post.validated? returns 1 or 0 <input type="checkbox" id="post_validate" name="post[validated]" value="1" checked="checked" /> <input name="post[validated]" type="hidden" value="0" /> check_box "puppy", "gooddog", {}, "yes", "no" <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" /> <input name="puppy[gooddog]" type="hidden" value="no" />

5.6.7.6. Options

Creates a select tag. Pass an array of choices:

<%= select :variable, :attribute, choices, options, html_options %>

Example:

select "post", "person_id", Person.find_all.collect {p [ p.name, p.id ] }, { :include_blank => true } <select name="post[person_id]"> <option></option> <option value="1" selected="selected">David</option> <option value="2">Sam</option> <option value="3">Tobias</option> </select> <%= collection_select :variable, :attribute, choices, :id, :value %>

5.6.7.7. Date and Time

<%= date_select :variable, :attribute, options %> <%= datetime_select :variable, :attribute, options %>

Examples:

date_select "post", "written_on" date_select "user", "birthday", :start_year => 1910 date_select "user", "cc_date", :start_year => 2005, :use_month_numbers => true, :discard_day => true, :order => [:year, :month] datetime_select "post", "written_on"

5.6.7.8. end_form Tag

<%= end_form_tag %>

Learn more: http://api.rubyonrails.com/classes/ActionView/Helpers/FormHelper.html.

5.6.8. Layouts

A layout defines the surroundings of an HTML page. You use it to define common look and feel. Layouts live in app/views/layouts :

<html> <head> <title>Form: <%= controller.action_name %></title> <%= stylesheet_link_tag 'scaffold' %> </head> <body> <%= yield %> # the content will show up here </body> </html> ---- class MyController < ApplicationController layout "standard", :except => [ :rss, :atom ] ... end ---- class MyOtherController < ApplicationController layout :compute_layout # this method computes the name of the layout to use def compute_layout return "admin" if session[:role] == "admin" "standard" end ... end

Layouts have access to the instance variables of the controller.

Learn more: http://api.rubyonrails.com/classes/ActionController/Layout/ClassMethods.html.

5.6.9. Partials

Partials are building blocks for creating views. They allow you to reuse commonly used display blocks. They are stored in files:

render :partial => 'product'

This command loads the partial in _product.rthml and passes the instance variable @product to it. The partial can access it using @product :

render :partial => 'product', :locals => { :product => @bought }

This command loads the same partial but assigns a different instance variable to it:

render :partial => 'product', :collection => @product_list

This renders the partial for each element in @product_list and assigns @product to each element. An iteration counter is automatically made available to the template with a name of the form partial_name_counter (in the previous example, product_counter ).

Learn more: http://api.rubyonrails.com/classes/ActionView/Partials.html.

Категории