开发者

How to output text in rthml without <%=variable%>

I've been looking around for a solution to this questi开发者_StackOverflow社区on 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.


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

- @products.each do |p|
  = @p.name


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


Use print instead of put.


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜