ERB模板删除尾线 [英] ERB Template removing the trailing line

查看:46
本文介绍了ERB模板删除尾线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用于发送电子邮件的ERB模板.

I have an ERB template for sending an email.

Name: <%= @user.name %>
<% if @user.phone.present? %>
Phone: <%= @user.phone %>
<% end %>
Address: <%= @user.address %>

Phone 为空时,我正在尝试删除 Name Address 之间的空白行.

I am trying to remove the blank line between Name and Address when Phone is empty.

返回结果

Name: John Miller 

Address: X124 Dummy Lane, Dummy City, CA

预期结果

Name: John Miller 
Address: X124 Dummy Lane, Dummy City, CA

我尝试使用<%-%> 标记(以删除结尾的新行),但没有成功.

I have tried to use <%--%> tags(to remove the trailing new line) without any success.

Name: <%= @user.name %>
<%- if @user.phone.present? -%>
Phone: <%= @user.phone %>
<%- end -%>
Address: <%= @user.address -%>

如何解决此问题?

PS::我在Rails 2.3.8上.

PS: I am on Rails 2.3.8.

注释1

现在,我正在使用红宝石黑客解决此问题.

Right now, I am working around the issue using 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

查看代码

<%= display_fields(["Name", "Phone", "Address"], @user) %>

但是对于我来说,这看起来很笨拙.我想知道是否有人能够在ERB视图模板中使用<%-%> .

But this looks quite clunky to me. I am interested in knowing if anybody has been able to get the <%--%> working in ERB view templates.

推荐答案

要启用修剪模式,您必须以'-'作为第三个参数实例化ERB对象

To enable trim mode you have to instantiate the ERB object with '-' as the third parameter

ERB.new(template, nil, '-')

这篇关于ERB模板删除尾线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆