0

我有一个循环输出我从网站上获取的一些信息。为了使信息以可读的方式显示,我<br>在字符串中添加了一个。但是,当它运行时,它会显示<br>,转义 html。我使用了 html_safe 和 raw 但都不起作用。代码有什么问题?代码在视图主页中调用(别担心,一旦代码工作,我会移动它)。

<%= 

 require 'rubygems'
 require 'nokogiri'
 require 'open-uri'


time = Time.new
month = I18n.t("date.abbr_month_names")[time.month]
day = time.day
"#{month} #{day}"

#United States
cities = [
   "sfbay", "losangeles", "athensga", "phoenix", "santabarbara", "denver",
   "panamacity", "miami", "austin", "bakersfield", "keys", "newyork"
]

cities.map do |city|

#Search Terms
search_terms = ["mechanic", "car", "tech"]

search_terms.map do |term|

  escaped_term = CGI.escape(term)

  url = "http://#{city}.craigslist.org/search/jjj?query=#{escaped_term}&catAbb=jjj&
  srchType=A"

  doc = Nokogiri::HTML(open(url))

  doc.css(".row").map do |row|

      date = row.css(".itemdate").text

      a_tag = row.css("a")[0]

      text = a_tag.text

      link = a_tag[:href]

      if date = "#{month} #{day}"
        @strings << "#{date} #{text} #{link}"
      end

  end

 end

end

%>
4

2 回答 2

0
doc.css(".row").map do |row|
  date = row.css(".itemdate").text
  a_tag = row.css("a")[0]
  text = a_tag.text
  link = a_tag[:href]
  if date = "#{month} #{day}"
    "<br/>".html_safe + "#{date} #{text} #{link}"
  end
end
于 2012-11-22T21:48:16.377 回答
0

嗯,完全不确定,但请尝试以下方法:

doc.css(".row").map do |row|

  date = row.css(".itemdate").text
  a_tag = row.css("a")[0]
  text = a_tag.text
  link = a_tag[:href]

  if date = "#{month} #{day}"
    @string = "#{date} #{text} #{link}<br />"
  end

end.html_safe

另一种方法,不是解决你的问题,而是在每行显示 br :

# in controller or whatever
@strings = []
if date = "#{month} #{day}"
  @strings << "#{date} #{text} #{link}"
end

# in the view:
<%= raw(@strings.join('<br />')) %>
于 2012-11-22T21:49:43.883 回答