Block comments in html.erb templates in rails Block comments in html.erb templates in rails ruby-on-rails ruby-on-rails

Block comments in html.erb templates in rails


Use this for commenting single lines:

<%# your_ruby_code %>

For multiple lines, the

<% =begin %>  <% ruby_code %><% =end %>

What you said would work.


I wouldn't count as a solution, but perhaps enclosing the chunk between an

<% if false %>   ...<% end %>

or if you feel a little dirty, create a helper that simply outputs nothing.

I've never needed it, but I'm stumbled there seems to be no out-of-the-box solution for this.


The =begin approach is annoying because:

  1. It doesn't work for mixed HTML and Ruby (or just HTML) that's on a single line
  2. It's annoying to type

The <% if false %> approach works, but it looks weird and doesn't give anyone else who looks at your code a hint about your intentions.

My solution is as follows:

In application_helper.rb, add a method so:

def commentend

Then in your view template, you can say:

<% comment do %>Some stuff that won't be rendered...<% end %>

This works because any Ruby method can take a block, but will silently ignore the passed-in block if your method doesn't include a yield.