What <%- and -%> does on Ruby on Rails?
The Rails documentation only has a very short description for it:
<%- and -%> suppress leading and trailing whitespace, including the trailing newline, and can be used interchangeably with <% and %>.
I use '_' to represent a white space and '\n' for a newline character so that you can see these.
If the rails code is as follows:
source
__<% if something %>\n
____hello\n
__<% end %>\n
This produced following HTML code:
output
__\n
____hello\n
__\n
The leading and trailing whitespaces, including the trailing new line of Rails tags are actually output and produces three lines.
source
__<% if something -%>\n
____hello\n
__<% end %>\n
By changing the first %> with -%>, the trailing newline is omitted and the result looks like as follows. "hello" has six spaces (two spaces from the if line and four of them from the hello line):
output
______hello\n
__\n
By replacing <% with a <%-, it removes two leading whitespaces:
source
__<%- if something -%>\n
____hello\n
__<% end %>\n
output
____hello\n
__\n
By replacing all the <% and %> with <%- and -%>, you can get just the hello line:
source
__<%- if something -%>\n
____hello\n
__<%- end -%>\n
output
____hello\n
However, the sad part is that this won't work is there's any characters in the line.
source
leading_<%- if -%>_trailing
This doesn't trim leading/trailing spaces and produces following result...:
output
leading__trailing
Unless you use <%- and -%> in a pure Rails tag only lines, it doesn't have any meaningful effect.
(11/03/2009)