Rails Helpers:在helper方法中的content_tag末尾添加换行符

时间:2016-02-26 16:38:54

标签: html ruby-on-rails ruby

我为Contact模型提供了以下帮助方法:

def list_offices_if_present(contact)
  if contact.locations.any?
    content_tag :span, "Works out of: #{contact.offices_list}" + tag(:br)
  end
end

这是在content_tag

中调用的方法定义
#models/contact.rb
class Contact < ActiveRecord::Base
  ...
  def offices_list
    offices_names = []
    locations.each{|location|  office_names << location.office_name}
    return office_names.join(", ")
  end
end

我这样称呼这个帮助:

<p>
  <%= list_offices_if_present(@contact) %>
  <%= list_phone_if_present(@contact)   %>
<p>

问题是<br>标记呈现为文本,而不是实际的换行符,如下所示:

Works out of: Some Location <br /> Phone: 402-555-1234  

如何在帮助方法中的content_tag末尾添加换行符?

3 个答案:

答案 0 :(得分:1)

Rails自动转义html实体,你可以使用:

content_tag :span, "Works out of: #{contact.offices_list}".html_safe + tag(:br)

答案 1 :(得分:1)

content_tag(:span, "Works out of: #{contact.offices_list}" + raw("<br>"))

答案 2 :(得分:0)

我认为您的问题是以下代码行

content_tag :span, "Works out of: #{contact.offices_list}" + tag(:br)

执行
content_tag(:span, "Works out of: #{contact.offices_list}" + tag(:br))

注意tag(:br)"Works out of: #{contact.offices_list}"连接为第二个参数。

要解决此问题,请添加一对明确的括号:

content_tag(:span, "Works out of: #{contact.offices_list}") + tag(:br)