【问题标题】:How to post-process HTML to add "target blank" to all links in Ruby?如何对 HTML 进行后处理以向 Ruby 中的所有链接添加“目标空白”?
【发布时间】:2016-11-21 14:36:43
【问题描述】:

如何对 HTML 进行后处理以将“目标空白”添加到 Ruby 中的所有链接?

我目前正在使用 Rinku (gem) 来自动链接文本,效果很好。

但是,我正在对 HTML 进行后处理,并且某些链接已经是链接,因此不会使用 Rinku 进行处理。

如何将目标空白属性添加到这些属性中?

application_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

【问题讨论】:

标签: html ruby-on-rails ruby post-processing


【解决方案1】:

我用 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

【讨论】:

    猜你喜欢
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多