Ruby on rails 将{phrase}替换为<;a href="/短语&燃气轮机;短语</a>;在轨

Ruby on rails 将{phrase}替换为<;a href="/短语&燃气轮机;短语</a>;在轨,ruby-on-rails,ruby,Ruby On Rails,Ruby,我希望使用rails(erb.html文件)搜索{phrase}并将其替换为。需要替换多个短语,并且这些短语事先不知道 完整示例: Hi{各位},我真的很喜欢{rubyonrails} 需要成为 Hi, 这适用于用户生成的内容站点()您可以使用gsub来完成此操作 irb(main):001:0> str = " I have written this phrase statement, I want to replace occurences of all phrase with oth

我希望使用rails(erb.html文件)搜索{phrase}并将其替换为
。需要替换多个短语,并且这些短语事先不知道

完整示例:

Hi{各位},我真的很喜欢{rubyonrails}

需要成为

Hi,


这适用于用户生成的内容站点()

您可以使用gsub来完成此操作

irb(main):001:0> str = " I have written this phrase statement, I want to replace occurences of all phrase with other statement"
=> " I have written this phrase statement, I want to replace occurences of all phrase with other statement"
irb(main):002:0> str.gsub("phrase",'<a href="/phrase">phrase</a>')
=> " I have written this <a href=\"/phrase\">phrase</a> statement, I want to replace occurences of all <a href=\"/phrase\">phrase</a> with other statement"
irb(main):001:0>str=“我已经写了这个短语语句,我想用其他语句替换所有短语的出现”
=>“我已经写了这个短语语句,我想用其他语句替换所有短语的出现”
irb(主要):002:0>str.gsub(“短语”),“”)
=>“我已编写此语句,我想用其他语句替换所有出现的语句”

它是简单的regexp,只需使用

your_string.gsub(/{(.*?)}/, '<a href="\\1">\\1</a>')
your_string.gsub(/{(.*)}/,“”)
例如:

"{aaa} is not {bbb} you know".gsub(/{(.*?)}/, '<a href="/\\1">\\1</a>')
“{aaa}不是{bbb}你知道的”。gsub(/{(.*?}/,”)
将产生

<a href="/aaa">aaa</a> is not <a href="/bbb">bbb</a> you know
你不知道吗

只需在erb中使用助手即可。例如:

tag\u helper.rb:

module TagHelper
  def atag(phrase)
    "<a href='/#{phrase}'>#{phrase}</a>"
  end
end
<%= atag('guys')%>
模块TagHelper
def atag(短语)
""
结束
结束
some.html.erb:

module TagHelper
  def atag(phrase)
    "<a href='/#{phrase}'>#{phrase}</a>"
  end
end
<%= atag('guys')%>

更好的方法是使用降价输出引擎(最强大的引擎之一)

您必须创建一个:

#lib/custom_renderer.rb
类自动链接<红地毯::渲染::HTML
def auto_link(短语)#->将需要搜索内容。可以进一步研究吗
链接到短语“/{phrase}”
结束
结束
#控制器
markdown=red地毯::markdown.new(自动链接,自动链接:“ruby on rails”)

我对Ruby没有把握。。。但regex能做到吗?这很简单。。。匹配此
{([a-zA-Z]+)}
看不出为什么不匹配,我将尝试,谢谢。请重新检查您的示例。我想你错过了
的结尾,伙计们
我不会事先知道“短语”,我正在处理的是用户生成的内容。你可以使用str.gsub(变量“”)因此,我不再将短语作为字符串传递变量传递。实际上,我已经在这个应用程序上使用了红毯,如果gsub答案不起作用,我将探索这个选项。谢谢,这正是我所需要的!