[英]variable from controller into view in rails?
I know this might be a dumb question. 我知道这可能是一个愚蠢的问题。 I'm trying to use this xml parser
我正在尝试使用此xml解析器
http://nokogiri.rubyforge.org/nokogiri/Nokogiri.html http://nokogiri.rubyforge.org/nokogiri/Nokogiri.html
I've put the code below in a controller in a bringRSS method(?), and it works fine in IRB. 我已经将代码放在一个bringRSS方法(?)中的控制器中,并且在IRB中可以正常工作。 But how do I get values for puts link.content into my views
但是我如何获取将link.content放入视图的值
def bringRSS
require 'nokogiri'
require 'open-uri'
# Get a Nokogiri::HTML:Document for the page we’re interested in...
doc = Nokogiri::HTML(open('http://www.google.com/search?q=tenderlove'))
# Do funky things with it using Nokogiri::XML::Node methods...
####
# Search for nodes by css
doc.css('h3.r a.l').each do |link|
puts link.content
end
####
# Search for nodes by xpath
doc.xpath('//h3/a[@class="l"]').each do |link|
puts link.content
end
####
# Or mix and match.
doc.search('h3.r a.l', '//h3/a[@class="l"]').each do |link|
puts link.content
end
end
Your method is a rails action ? 您的方法是不正确的动作? If so, the "puts" method is inappropriate.
如果是这样,则“ puts”方法是不合适的。 You should define some global vars that'll be accessible in the view.
您应该定义一些可以在视图中访问的全局变量。
@css_content = Array.new
doc.css('h3.r a.l').each do |link|
@css_content << link.content
end
You define an @css_content array which contains every of your links. 您定义一个@css_content数组,其中包含每个链接。 And in your view you can use that var just like you usually use them in views.
在您的视图中,您可以像通常在视图中使用它们一样使用该var。
The use of puts in a Rails action will throw an exception. 在Rails操作中使用puts将引发异常。
Instead just assign the data to an instance variable, like this: 而是仅将数据分配给实例变量,如下所示:
@link_content = []
...
doc.css('h3.r a.l').each do |link|
@link_content << link.content
end
...
You can access it later in your views with the same name 您以后可以在视图中使用相同名称访问它
Technically, you could write directly to your response, as it behaves more or less like the object you puts
to in IRB. 从技术上讲,您可以直接写您的响应,因为它的行为或多或少类似于您
puts
IRB中的对象。 But as mentioned above, the Rails way of doing it is to use the controller to assign to instance vars and your view to render them. 但是如上所述,Rails的实现方式是使用控制器分配给实例var,然后使用视图呈现它们。
As a benefit, you'll be able to use some really nice Ruby when assigning: 作为好处,您可以在分配时使用一些非常好的Ruby:
@links = doc.css('h3.r a.l').map{|link|link.content}
will map what each object's content
method returns, just like you did above. 就像上面一样,将映射每个对象的
content
方法返回的content
。 And since Rails extends this by giving symbol objects a to_proc method, you could shorten it to 而且由于Rails通过为符号对象提供to_proc方法来扩展它,因此您可以将其缩短为
@links = doc.css('h3.r a.l').map(&:content)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.