不,如果trim_mode 是-,则ERB 省略以-%> 结尾的空行。
查看第一个代码及其输出:
require 'erb'
erb = ERB.new <<_, 0, '-'
<% teams.each_with_index do |t,i| -%>
<%= ',' unless i == 0 %> # here I have removed `-`
<%= t -%>
<%- end %>
_
teams = %w( India USA Brazil )
puts erb.result binding
# >>
# >> India,
# >> USA,
# >> Brazil
现在看看下面代码中-%>中-的效果:
require 'erb'
erb = ERB.new <<_, 0, '-'
<% teams.each_with_index do |t,i| -%>
<%= ',' unless i == 0 -%>
<%= t -%>
<%- end %>
_
teams = %w( India USA Brazil )
puts erb.result binding
# >> India,USA,Brazil
还有,
require 'erb'
erb = ERB.new <<_, 0, '-'
<% teams.each_with_index do |t,i| -%> <%= ',' unless i == 0 -%>
<%= t -%>
<%- end %>
_
teams = %w( India USA Brazil )
puts erb.result binding
# >> India ,USA ,Brazil
我认为ERB 方面没有任何东西可以去除空白。摆脱这种情况的一种方法是调整 ERB 模板 本身。
require 'erb'
erb = ERB.new <<_, 0, '-'
<% teams.each_with_index do |t,i| -%><%= ',' unless i == 0 -%>
<%= t -%>
<%- end %>
_
teams = %w( India USA Brazil )
puts erb.result binding
# >> India,USA,Brazil
Railish 方式是:
<%= teams.map { |t| link_to t.name, team_path(t) }.join(', ').html_safe %>
这是关于第一个代码的一些推理:
<% teams.each_with_index do |t,i| -%> 将在您为每次迭代添加 - 时被删除。现在下一个是<%= ',' unless i == 0 -%>,它不会是第一次出现,而是下一次迭代。但是每次, 都会没有尾随空格,因为它之前的erb标签被-删除。
这是关于第二个代码的一些推理:
<% teams.each_with_index do |t,i| -%> 将在您为每次迭代添加 - 时被删除。现在下一行是<%= ',' unless i == 0 -%>,它不会第一次出现,但会继续下一次迭代。现在这有一些额外的缩进空格,这导致每个,之前都有一个空格。 [单个空格],