如何对 HTML 进行后处理以将“目标空白”添加到 Ruby 中的所有链接?
我目前正在使用 Rinku (gem) 自动链接文本,效果很好。
但是,我正在对 HTML 进行后处理,一些链接已经是链接,因此没有使用 Rinku 进行处理。
我怎样才能将目标空白属性添加到那些?
应用程序 Controller .rb
def text_renderer text
AutoHTML.new(text).render
end
auto_html.rb
class AutoHTML
include ActionView::Helpers
def initialize text
@text = text
end
def render
text = prepare @text
text = auto_link(text)
text.html_safe
end
private
def prepare text
if text.nil? || text.empty?
""
else
text
end
end
def auto_link text
Rinku.auto_link(text, :all, 'target="_blank"')
end
end
最佳答案
我用 nokogiri 实现了一个解决方案:
def self.a_with_target_blank(body)
doc = Nokogiri::HTML(body)
doc.css('a').each do |link|
link['target'] = '_blank'
# Worried about @spickermann's security concerns in the comment? then
# consider also to add:
#
# link['rel'] = 'noopener'
#
# In any case, this security hole has been solved in modern browsers, (check
# https://github.com/whatwg/html/issues/4078) so unless you're supporting
# very old browsers, there's no much to worry about.
end
doc.to_s
end
关于html - 如何对 HTML 进行后处理以将 "target blank"添加到 Ruby 中的所有链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38445999/