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 ...

Get Learning Rails now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.