O'Reilly logo

Learning Rails: Live Edition by Edd Dumbill, Simon St. Laurent

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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-9, that takes advantage of the count variable in the controller. (This example is part of the ch02/hello003 code sample.)

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

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

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

</body>
</html>

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.

Note

The for loop is familiar to developers from a wide variety of programming languages, but it’s not especially idiomatic Ruby. Ruby developers would likely use a times construct instead, such as:

<% @count.times do %>
<p><%=h @bonus %></p>
<% end %>

Depending on your fondness for punctuation, you can also replace the do and end with curly braces, as in:

<% @count.times {  %>
<p><%=h @bonus %></p>
<% } %>

As always, you can choose the approach you find most comfortable.

The loop will run three times, counting up to the value the controller set for the count variable. As a result, “This message came from the controller.” ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required