How do I run multiple lines of Ruby in html.erb fi

2020-06-07 04:32发布

问题:

I'm using Ruby on Rails and need to run a block of Ruby code in one of my html.erb files. Do I do it like this:

<% def name %>
<% name = username %>
<%= name %>

or like this:

<% def name
name = username %>
<%= name %>

Thanks for reading.

回答1:

It is unusual to define a method in an ERB file, so I recommend against it.

If you want to call a block like #each, you can do something like the following:

<% names.each do |name| %>
  <%= name %>
<% end %>

Don't forget the <% end %>.



回答2:

If you need extra functions in your view, you normally declare those inside a helper.

For each controller, if there is a helper it is automatically loaded. For instance, if you have a PeopleController, in the app/helpers folder, there should be a people_helper.rb, and it should look like this

module PeopleHelper
  def name
    #do something
    username
  end
end

Another, very clean alternative, is to use the Presenter pattern, but i think it is less common (unfortunately).

Otherwise, if you do need multiple lines of ruby code inside a erb view, which i try to avoid, i prefer the following style:

<%
   counter_1 = 0
   counter_2 = 1
   do_some_more_prep_here
 %>
<% @records.each do |rec|%>
  <%# do something with the prepped date in each row %>
<% end %>

Also for me code indentation is more important than html indentation, so i will prefer something like

<table> 
  <% @rows.each do |row| %>
    <tr>
      <td><%= row.item1 %></td>
      <% if row.some_test %>
        <td><%= row.item2 %></td>
      <% end %>
    </tr>
  <% end %>
</table>

But i am always very interested to hear different opinions in this matter.



回答3:

I can imagine someone needing it in one particular template (no point in creating a helper) to not duplicate html markup. That is, when resulting html page has a couple of similar blocks of html markup. Though, it can easily be abused (unreadable code).

<% def f1(a, b, c) %>
  test: <%= a %>, <%= b %>, <%= c %>
<% end %>

<% f1(1, 2, 3) %>
<% f1(4, 5, 6) %>