可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
This question already has an answer here:
I have started some rails tutorials and noticed that some of the view code blocks are like
and other code blocks are like
What is the difference between -%> and %>
If you know of some good syntax references you can point me to, that would also be helpful.
回答1:
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:
Hi
It'll produce:
Hi
and not this:
Hi
回答2:
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 %>
.
回答3:
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
is compiled to:
Lorem ipsum dolor sit amet
And…
%left_tag %inside> %right_tag
is compiled to:
If you're not using HAML it's definitely worth checking out.
回答4:
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("\nb").result == "a\nb" or raise begin ERB.new("\nb").result; rescue SyntaxError ; else raise; end ERB.new("\nb" , nil, '-').result == "a\nb" or raise ERB.new("\nb" , nil, '-').result == 'ab' or raise ERB.new(" \nb" , nil, '-').result == "a \nb" or raise ERB.new("\n b" , nil, '-').result == 'a b' or raise ERB.new("\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