ERB模板删除尾随线
我有一个用于发送电子邮件的ERB模板。
Name: Phone: Address:
我想在Phone
为空时删除Name
和Address
之间的空白行。
返回结果
Name: John Miller Address: X124 Dummy Lane, Dummy City, CA
预期结果
Name: John Miller Address: X124 Dummy Lane, Dummy City, CA
我试图使用标记(删除尾随的新行),但没有成功。
Name: Phone: Address:
我该如何解决这个问题?
PS:我在Rails 2.3.8上。
注1
现在我正在使用ruby hackery解决这个问题。
帮手方法:
def display_fields(names, user) names.collect do |name| value = user.send(name) "#{name}: #{value}" unless value.blank? end.compact.join("\n") end
查看代码
但这看起来很笨重。 我有兴趣知道是否有人能够在ERB视图模板中使用 。
要启用修剪模式,必须使用“ – ”作为第三个参数来实例化ERB对象
ERB.new(template, nil, '-')
我不得不将willmcneilly,RobinBrouwer和fbo的答案结合起来。
启用修剪模式
ERB.new(File.read(filename), nil, '-')
更改为 – %>
<% $things.each do |thing| -%> <% end -%>
最后,从dos转换为unix。 我在Vim中使用了以下内容:
:set fileformat=unix :w
试试这个:
Name: <%= @user.name %> <% unless @user.phone.blank? -%>Phone: <%= @user.phone %><% end -%> Address: <%= @user.address %>
另外,不知道这是否有效:
Name: <%= @user.name %> <%= "Phone: #{@user.phone}" if @user.phone.present? -%> Address: <%= @user.address %>
如果这也不起作用,这应该可以解决问题:
Name: <%= @user.name %><%= "\nPhone: #{@user.phone}" if @user.phone.present? %> Address: <%= @user.address %>
我有同样的问题,
这是由于空间字符afer %>
也许它会对你有所帮助
弗朗索瓦
根据最新的rails docs( http://guides.rubyonrails.org/v2.3.8/configuring.html#configuring-action-view ):
ActionView :: TemplateHandlers :: ERB.erb_trim_mode给出了ERB使用的修剪模式。 它默认为’ – ‘。
他们参考了ERB文档( http://www.ruby-doc.org/stdlib-2.0.0/libdoc/erb/rdoc/ERB.html#method-c-new )
If trim_mode is passed a String containing one or more of the following modifiers, ERB will adjust its code generation as listed: % enables Ruby code processing for lines beginning with % <> omit newline for lines starting with <% and ending in %> > omit newline for lines ending in %> - omit blank lines ending in -%>
所以你需要做的就是在你的结束erb标签中加上破折号,比如-%>
。 如果您看到意外结果,则可能需要使用修剪模式。
通过使用’>’选项,您将省略以%>结尾的行的换行符
ERB.new(template, nil, '>')
这意味着您可以像往常一样将Ruby代码包装在<%%>标记内。 不幸的是,我还没有找到一种方法来删除起始<%标记之前的空格。