【问题标题】:Creating a link with link_to and gsub使用 link_to 和 gsub 创建链接
【发布时间】:2014-06-25 22:08:26
【问题描述】:

我有一段文本被输入到 textarea 中,如果任何文本与 URI.regexp 匹配,我需要使用 textarea 中 a 标记上的 target: '_blank' 激活该链接。

这是我当前的代码。我还用.match 尝试了这个,这将是正确的

def comment_body(text)
  text = auto_link(text)

  text.gsub!(URI.regexp) do |match|
    link_to(match, match, target: '_blank')
  end
end

这个输出:

https://facebook.com">https://facebook.com在我看来

<a href="<a href=" https:="" facebook.com"="" target="_blank">https://facebook.com</a> 在被检查的 HTML 中。

gsub docs 中,它说元字符将按字面意思解释,我认为这让我很困惑。

关于如何正确构建此 URL 的任何提示?

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby link-to gsub


    【解决方案1】:

    auto_link gem 可以满足您的需求。

    您可以查看它的代码以了解它是如何使用 gsub 的。

    【讨论】:

    • 我在上面有一行,text = auto_link(text)。这已经在使用了。编辑了我上面的代码以反映它
    • 如果您已经在使用它,只需将选项传递给target="_blank",如下所示:auto_link(text, :all, :target => "_blank")
    【解决方案2】:

    编辑:此解决方案需要将 sanitize 设置为 false,这通常不是一个好主意!

    我找到了一个不使用 auto_link 的解决方案(我也在使用 Rails 5)。我知道这是一个过时的线程,但我花了一些时间试图找到一个允许插入 target="_blank" 的解决方案并找到了这个。在这里,我创建了一个帮助程序来在文本框中搜索文本以获取链接,然后添加实质上使它们在视图中可链接。

    def formatted_comment(comment)
        comment = comment.body
    
        URI.extract(comment, ['http', 'https']).each do |uri|
            comment = comment.gsub( uri, link_to(uri, uri, target: "_blank"))
        end
    
        simple_format(comment, {}, class: "comment-body", sanitize: false)
    end
    

    这里的关键是 simple_format 不断进行清理,因此添加 {} 和 sanitize:false 很重要。

    ***请注意,将 sanitize 设置为 false 可能会引发其他问题,例如允许 javascript 在评论中运行,但此解决方案将允许将 target="_blank" 插入链接。

    【讨论】:

      【解决方案3】:

      仅使用带有反向引用的简单gsub 的解决方案是这样的:(您当然可以修改正则表达式以满足您的需求。)

      str = 'here is some text about https://facebook.com and you really http://www.google.com should check it out.'
      
      linked_str = str.gsub( /((http|https):\/\/(www.|)(\w*).(com|net|org))/, 
                               '<a href="\1" target="_blank">\4</a>' )
      

      示例输出:

      print linked_str
      #=> here is some text about <a href="https://facebook.com" target="_blank">facebook</a> and you really <a href="http://www.google.com" target="_blank">google</a> should check it out.
      

      【讨论】:

      • 这不起作用。由于某种原因,a 标签中没有 target="_blank"
      • @Zack 这怎么可能?准确粘贴您的 HTML 输出内容。
      • 和我最初的帖子一样
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      • 2021-10-14
      • 2019-11-07
      相关资源
      最近更新 更多