Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block comments in html.erb templates in rails

People also ask

How do I comment in an ERB file in HTML?

To comment one line I must use 3 additional characters, and the block comment is nothing but code that will be not executed - no other color coding that makes it very unpractical to see which code is not executed on first look. @gotqn Then you will LOVE HAML!

How do you comment out in ERB?

%>\n <% end #____/\____/\____/\____%> . This makes the comment area obvious.

How do you comment out a block of code in Ruby?

The Ruby single-line comment begins with the # character and ends at the end of the line. Any characters from the # character to the end of the line are completely ignored by the Ruby interpreter. The # character doesn't necessarily have to occur at the beginning of the line; it can occur anywhere.

How do you comment code in Rails?

-- --> as a comment. As the other answers said, use <% #comment %> to comment within a Rails view.


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 comment
end

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.


<%#=

...commented
multiline
block...

%>

For block comments in templates, my text editor (Komodo) finds this variation on @Garfield's recommendation least obnoxious:

<%# A long multiline comment in a rails template ...
  # line 2
  # and so on ... 
  # %>

To comment out erb tags use the ruby comment hash symbol before the = sign in the opening tag

<p>
 This is some text I want to keep
 <%= @some_object.some_attribute %>
</p>
<p>
  I want to keep this text but comment out the erb tag
  <%#= @some_object.another_attribute %>
</p>
<!--
<p>
  I want all of this text commented out including the erb tag
  <%#= @some_object.some_attribute %>
</p>
-->
<!--
<p>
 I just want this html commented out but I want to keep the erb tag
 <%= @some_object.some_attribute %>
</p>
-->