简体   繁体   English

Ruby中的gsub方法

[英]gsub method in Ruby

I'm a RoR newbie, and I'm attempting to figure out how to get the gsub method to add html to my page. 我是RoR新手,并且试图弄清楚如何使用gsub方法将html添加到页面中。 Specifically, I'm attempting an exercise that, like Twitter, will route to an action that will list a Users tweets by linking their username. 具体来说,我正在尝试像Twitter这样的练习,该练习将路由到通过链接用户名列出用户tweet的操作。 So, the string @username within the content property will link to /tweets/username listing out of the user's tweets. 因此,content属性中的字符串@username将链接到/ tweets / username,该列表列出了用户的tweets。 I have the action and route completed, but I can't get the gsub to work correctly. 我的动作和路线已经完成,但是我无法让gsub正常工作。 Here's what I thought would work 这是我认为可行的

<%= content_tag :p, twet.content.gsub(/@[a-zA-z0-9]/, <html code here>)%>

but it doesn't. 但事实并非如此。 The html renders as text. html呈现为文本。 To try to get around this, I also tried to create a link_to helper method using the $1 variable 为了解决这个问题,我也尝试使用$ 1变量创建一个link_to helper方法。

<%= content_tag :p, twet.content.gsub(/@[a-zA-z0-9]/, link_to(("#{$1}", user_tweet_path($1)))%>

but that isn't working either. 但这也不起作用。 I've read other posts and learned that rails may not print html due to malicious code protection and $1 gets set after the sub, so I'm lost on how to make this work. 我读过其他文章,并了解到,由于恶意代码保护,rails可能无法打印html,并且在sub后面设置了$ 1,所以我对如何使此工作迷失了方向。

The variable twet needs to be set as html safe before it gets passed to content_tag . 在将变量twet传递给content_tag之前,需要将其设置为html安全。 Try this: 尝试这个:

<%= content_tag :p, twet.content.gsub(/@[a-zA-z0-9]/, <html code here>).html_safe %>

content_tag marks its output as HTML safe, but only after it has sanitized everything that was passed to it. content_tag其输出标记为HTML安全,但仅在其清除传递给它的所有内容之后再进行标记。

This isn't an answer to your question, but, besides the fact that you shouldn't do that in your view, your regexp pattern is flawed: 这不是您问题的答案,但是,除了您不应该这样做之外,您的regexp模式还有缺陷:

/@[a-zA-z0-9]/

Consider what it's doing: 考虑一下它在做什么:

[*'A'..'z', *'0'..'9'].join[/[a-zA-z0-9]+/]
 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz0123456789"

Az opens up the pattern to grab all characters from "A" to "z", including Az打开模式以捕获从“ A”到“ z”的所有字符,包括

[\]^_`

You probably don't want that. 您可能不想要那样。

Here's an example demonstrating it visually on Rubular.com. 这是一个在Rubular.com上直观演示的示例

尝试在第一种方法.html_safe添加到HTML字符串中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM