1

I've been looking around for a solution to this question for the last couple of days. It's a simple annoyance, but I hate not knowing how to do things...

Environment: Ruby, Rails, rhtml

The Problem: When I iterate a collection in rhtml I would like to reduce the number of <% %> and <%= %> tags I use. The following seems bloated:

Example

<% @products.each do |p| %>
  <%=  @p.name %>
<% end %>

EDIT: how do I exclude <%= %> inside of a block?

I would much rather do:

<% @products.each do |p| 
  puts @p.name 
end %>

Certain situations could allow for use of either... However, I know that I could do this with jsp:

<% for(int i=0; i<10;i++){
  System.out.print(i);
} %>

Thanks in advance for your input.

Chadwick
  • 283
  • 1
  • 2
  • 8

6 Answers6

5

if you want to be less verbose look at haml, with your example it will be :

- @products.each do |p|
  = @p.name
Mike
  • 5,165
  • 6
  • 35
  • 50
  • 2
    +1 on using Haml. It takes some getting used to at first, but after that I promise you won't look back. Your templates end up being a lot less noisy. – Mirko Froehlich Oct 24 '09 at 17:37
2
<% @products.each do |p| 
  _erbout << @p.name 
end %>

_erbout is the default name of the variable that ERB (the class that's parsing your .rhtml template) uses to build its output. This is pretty ugly, and feels a bit hacky to me, but it works.

No Surprises
  • 4,831
  • 2
  • 27
  • 27
  • Thanks for the help. Unfortunately that didn't work; it seems the _erbout variable isn't available. Error: undefined local variable or method `_erbout' for # – Chadwick Oct 23 '09 at 18:51
0

Use print instead of put.

0

Several other possibilities, depending on the context, if your view code seems too bloated:

  • Use partials. E.g.:

in your main file:

<%= render(:partial => "product", :collection => products) %>

and in the partial, just use:

<%= product.name %>

Now this seems contrived for a simple example such as this but assuming something more complex it abstracts away the looping and makes the code clearer.

  • Use helper methods
JRL
  • 76,767
  • 18
  • 98
  • 146
0

You could also try using something like haml to clean up the templates (along with helpers and partials).

CodeJoust
  • 3,760
  • 21
  • 23
0

You're going to have to use a <%= inside such a block. You can achieve the readability you want by using a <%= with a block:

<%= @products.map do |p|
      p.name
    end.join("\n") %>
cldwalker
  • 6,155
  • 2
  • 27
  • 19