如何让 link_to 在新窗口中打开外部 URL? [英] How do I make link_to open external URLs in a new window?

查看:25
本文介绍了如何让 link_to 在新窗口中打开外部 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转换 rails 2.3 站点,以便在新窗口中打开所有外部 URL.我可以通过每次调用 link_to 并添加 :target =>'_blank',但我想一步完成所有链接,现在和将来.有没有办法让我修改 link_to 以获得所需的行为?

I need to convert a rails 2.3 site so that all external URLs open in a new window. I could go though every call to link_to and add :target => '_blank', but I'd like to do it in one step for all links, present and future. Is there a way I can monkey patch link_to to get the desired behaviour?

推荐答案

最后我选择了这个,在一个初始化程序中:

In the end I went with this, in an initialiser:

module ExternalLinksInNewTabs
  def new_tab_link_to *args, &block
    if block_given?
      options = args.first || {}
      html_options = args[1] || {}

      if options.is_a? String
        if ExternalLinksInNewTabs.is_external_link? @controller.request.host, options
          html_options[:target] = '_BLANK'
        end
      end

      same_tab_link_to options, html_options, &block
    else
      name = args.first
      options = args[1] || {}
      html_options = args[2] || {}

      if options.is_a? String
        if ExternalLinksInNewTabs.is_external_link? @controller.request.host, options
          html_options[:target] = '_BLANK'
        end
      end

      same_tab_link_to name, options, html_options
    end
  end

  def self.is_external_link? host, url
    host.sub! /^www\./, ''
    url =~ /^http/i && url !~ /^http:\/\/(www\.)?#{host}/i
  end
end

module ActionView
  module Helpers
    module UrlHelper
      include ExternalLinksInNewTabs

      alias_method :same_tab_link_to, :link_to
      alias_method :link_to, :new_tab_link_to
    end
  end
end

这篇关于如何让 link_to 在新窗口中打开外部 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆