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.
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.” will
appear three times, as shown in Figure 2-6.
It’s not the most exciting page, but it’s the foundation for a lot more work to come.
If you’re picky about the amount of whitespace you put into documents, perhaps because you’re
generating text files or emails, you may also want to know how to
suppress the extra whitespace created by the loop’s markup. It’s
easy—just replace the closing %>
with -%>
. Any trailing newlines will be stripped. (It won’t look
any different in the HTML, though.)