【问题标题】:Suppressing spaces in ERB template抑制 ERB 模板中的空格
【发布时间】:2015-03-03 16:11:12
【问题描述】:

为什么会产生所需的输出(团队名称列表,用逗号分隔):

<% teams.each_with_index do |t,i| -%><%= ',' unless i == 0  -%>
    <%= link_to t.name, team_path(t) -%>
<%- end %>

输出:一、二、三

这不是:

<% teams.each_with_index do |t,i| -%>
    <%= ',' unless i == 0  -%>
    <%= link_to t.name, team_path(t) -%>
<%- end %>

输出:一、二、三

我的理解是“-%>”应该在逗号前取消空格。但显然我的理解(或 Rails 4.2.0)是错误的。

【问题讨论】:

标签: ruby-on-rails erb


【解决方案1】:

不,如果trim_mode-,则ERB 省略以-%&gt; 结尾的空行。

查看第一个代码及其输出:

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

现在看看下面代码中-%&gt;-的效果:

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 %>

这是关于第一个代码的一些推理

&lt;% teams.each_with_index do |t,i| -%&gt; 将在您为每次迭代添加 - 时被删除。现在下一个是&lt;%= ',' unless i == 0 -%&gt;,它不会是第一次出现,而是下一次迭代。但是每次, 都会没有尾随空格,因为它之前的erb标签被-删除。

这是关于第二个代码的一些推理

&lt;% teams.each_with_index do |t,i| -%&gt; 将在您为每次迭代添加 - 时被删除。现在下一行是&lt;%= ',' unless i == 0 -%&gt;,它不会第一次出现,但会继续下一次迭代。现在这有一些额外的缩进空格,这导致每个之前都有一个空格[单个空格],

【讨论】:

  • 第二个例子中没有换行的原因是HTML忽略了文本中的换行。
  • @Beartech 我同意你的看法
  • 很好的答案 - 感谢您添加我真正需要的 rails 方式。遗憾的是 ERB 没有一种机制来抑制 之前的前导空格
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 2016-07-07
  • 2012-06-03
  • 1970-01-01
相关资源
最近更新 更多