我正在使用 Nokogiri(它没有好的文档)从 Reddit 中删除链接和内容。
这是我在 haml 中的观点
%h1 Giri with Rails
%p
Read top Current headlines about #{link_to "Rails on Reddit", 'http://www.reddit.com/r/rails/'}
%ul.list-group
- @link.each do |url|
= link_to url[:href], target: '_', class: "list-group-item" do
%span.glyphicon.glyphicon-globe
#{url[:content]}
呈现如下:
这是其背后的逻辑/模型:
require 'nokogiri'
require 'open-uri'
class RedditScraper
def initialize
@headline = []
end
def search
doc = Nokogiri::HTML(open("http://www.reddit.com/r/rails/"))
doc.css('a.title').each do |link|
if link['href'].include?('http')
@headline << { content: link.content, href: link['href']}
else
@headline << { content: link.content, href: "http://reddit.com" + link['href'] }
end
end
@headline
end
end
这是我们的瘦 Controller :
class SearchController < ApplicationController
def index
@link = RedditScraper.new.search
end
end
现在,正如您在图片中看到的,我正在将 %span.glyphicon.glyphicon-link
添加到我的 View 中,它会显示所有链接。但由于很少有链接与 Reddit 本身相关,而不是外部链接,我想更改该图标(并添加额外的样式,例如粗体链接或颜色...)。
我试过像这样在模型中这样做:
icon = "<span class="glyphicon glyphicon-link"></span>"
@headline << { content: link.content + icon, href: link['href']}
但是没有用。我想根据链接类型添加额外的内容。
谢谢!
最佳答案
如果你想追求纯度,我会将 class
字段添加到 @link
条目,使用该类呈现 link_to
,然后通过 CSS 提供颜色和图标。 (:before
太酷了。)
关于jquery - 如何将 'html element' 添加到 Rails Controller 的 View 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24047382/