Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

2. Rails on the Web > Adding Logic to the View

Adding Logic to the View

You can also put more sophisticated logic into the views, thanks to the <% and %> tags. (The opening tag lacks the = sign.) These tags let you put Ruby code directly into your ERb files. We’ll start with a very simple example, shown in Example 2-7, that takes advantage of the count variable in the controller. (This example is part of the ch02/hello03 code sample.)

Example 2-7. Modifying index.html.erb to present the @bonus message as many times as @count specifies

<h1><%= @message %></h1>
<p>This is a greeting from app/views/hello/index.html.erb</p>

<% for i in 1..@count %>
  <p><%= @bonus %></p>
<% end %>

The count variable now controls the number of times the bonus message appears because of the for...end loop, which will simply count from 1 to the value of the count variable.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial