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

42,355

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

Solution 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.

Share:
42,355
ben
Author by

ben

Updated on February 21, 2020

Comments

  • ben
    ben about 4 years

    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.