57
votes

I have started some rails tutorials and noticed that some of the view code blocks are like

<h1><%= @subject.name -%></h1>

and other code blocks are like

<h1><%= @subject.name %></h1>

What is the difference between -%> and %>

If you know of some good syntax references you can point me to, that would also be helpful.

4
This one was asked before the referenced one was. Though I trust our moderators know what they are doing. - Brettski

4 Answers

89
votes

The extra dash makes ERB not output the newline after the closing tag. There's no difference in your example, but if you have something like this:

<div>
  <% if true -%>
  Hi
  <% end -%>
</div>

It'll produce:

<div>
  Hi
</div>

and not this:

<div>

  Hi

</div>
5
votes

I'm pretty sure - before %> is no longer necessary, and should be left out.

At least in Chrome, the generated html looks the same using -%> or %>.

4
votes

If you use HAML rather than ERB you can do something similar with a less than or greater symbol than after your tag.

> will remove any whitespace around your tag and < will remove any whitespace within it.

.float-left<
  %p
    Lorem ipsum dolor sit amet

is compiled to:

<div class="float-left"><p>
  Lorem ipsum dolor sit amet
</p></div>

And…

%left_tag
%inside>
%right_tag

is compiled to:

<left_tag /><inside /><right_tag />

If you're not using HAML it's definitely worth checking out.

3
votes

UPDATE: This answer was wrong, see https://stackoverflow.com/a/25626629/895245 instead.


In Ruby 2.1 (not necessarily with Rails), the - removes one trailing newline:

  • the newline must be the first char after the >
  • no spaces are removed
  • only a single newline is removed
  • you must pass the '-' option to use it

Examples:

require 'erb'
ERB.new("<%= 'a' %>\nb").result              == "a\nb"  or raise
begin ERB.new("<%= 'a' -%>\nb").result; rescue SyntaxError ; else raise; end
ERB.new("<%= 'a'  %>\nb"  , nil, '-').result == "a\nb"  or raise
ERB.new("<%= 'a' -%>\nb"  , nil, '-').result == 'ab'    or raise
ERB.new("<%= 'a' -%> \nb" , nil, '-').result == "a \nb" or raise
ERB.new("<%= 'a' -%>\n b" , nil, '-').result == 'a b'   or raise
ERB.new("<%= 'a' -%>\n\nb", nil, '-').result == "a\nb"  or raise

Doc: http://ruby-doc.org/stdlib-2.1.1/libdoc/erb/rdoc/ERB.html

Rails 4.1 documents this at http://api.rubyonrails.org/classes/ActionView/Base.html, and appears to:

However, Rails 4.1 does remove trailing whitespaces as documented while pure ERB does not, so there may be other differences.

Also, it is not removing the leading newlines as documented: it might be a documentation bug. Opened an issue at: https://github.com/rails/rails/issues/16766