How do I comment out code in my views?

You’ve been writing a view – it’s got quite a bit of code in there and you need to play around with a few bits and pieces. So it’s time to comment a chunk of the code out so you can adjust the layout.

First try – let’s use some HTML comments <!-- IGNORE ME -->. And that works great for your markup – but your Ruby still gets executed.

How do you comment out lines in ERB?

Well the simplest is to use an ERB comment. Instead of <%= @person.name %> you can use <%# @person.name %> and your Ruby code is ignored.

But that only works for single lines.

There must be a way to do this for multiple lines … it’s just not immediately obvious.

Ruby has a block comment syntax that looks a bit weird:

And you can use that in your ERB template:

I told you. Weird eh?

You definitely don’t want that all over your code.

However, there’s another little trick you can use that is technically weird but works great.

In your application_helper.rb define a new method:

Then in your views you can use it like so:

Your view is now calling this “ignore” method and passing it the block which has the code you want to ignore. Normally a helper method returns some content that gets rendered into your template – whether that content comes from parameters or by manipulating a block.

But your ignore method does nothing. So the block is ignored and your view is code-free.

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe