Search code examples
ruby-on-railsrubyblockerb

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


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.


Solution

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