views:

150

answers:

6

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.

+2  A: 
<% @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
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 #<ActionView::Base:0x0000001c6d28d0 Ah well, I guess I'll just have to get used to this small oddity
Chadwick
A: 

Use print instead of put.

Elizabeth Buckwalter
A: 

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
A: 

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

CodeJoust
+5  A: 

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

- @products.each do |p|
  = @p.name
Mike
+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
A: 

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") %>