2014-06-25 46 views
1

我有一个文本正文被送入textarea,如果任何文本匹配URI.regexp,我需要使该链接在文本区域a标记上的target: '_blank'处于活动状态。创建link_to和gsub链接

这是我目前的代码。我也试图与.match这将correc

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在我看来

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

gsub docs它说元字符将被字面解释,这是我相信这在我这里搞砸了。

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

谢谢!

回答

1

auto_link宝石确实是你所需要的。

你可以看看它的代码,看看它如何使用gsub。

+0

我上面有一行,'text = auto_link(text)'。这已经在使用中。编辑我的代码以反映它 –

+0

如果您已经在使用它,只需传递选项以使'target =“_ blank”'像这样:'auto_link(text,:all,:target =>“_blank”)' – San

-1

只使用一个简单的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. 
+0

不工作。由于某种原因,a标签中没有target =“_ blank” –

+0

@Zack这怎么可能?正好粘贴HTML输出的内容。 – fyz

+0

和我最初的帖子一样 –

0

编辑:此解决方案需要设置清理为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保持消毒,所以添加{}和消毒:false都很重要。

***请注意,将sanitize设置为false可能会导致其他问题,如允许javascript在注释中运行,但此解决方案将允许将target =“_ blank”插入到链接中。