简体   繁体   English

Rails-无法让gsub替换字符串文本

[英]Rails - Cant get gsub to work to replace string text

I'm using the liquid gem and a wysiwyg editor for user posts. 我正在使用液态宝石和所见即所得的编辑器来发布用户帖子。 I'm trying to replace some of the content submitted before it is displayed. 我正在尝试替换显示之前提交的某些内容。 To do this I have tried .gsub but it isn't working at all 为此,我尝试了.gsub,但它根本不起作用

 <% template = Liquid::Template.parse(@category.template)  %>

 <% render = template.render(@keys_values_hash) %>

 <% content = render.gsub!('data-imgslap=', 'data-slap=') %>

 <% content.html_safe %>

The content is displayed fine and it all works but the text isnt replaced from gsub 内容显示正常,一切正常,但文本未从gsub替换

I want it to just replace one thing so I know it works. 我希望它只是替换一件事,所以我知道它是有效的。 But once that works I want to replace a couple of things. 但是一旦可行,我想替换几件事。 How would I use gsub to replace say 'text1', 'replacement1' and 'text2', 'replacement2' and why wont it work for just one replacement like I have setup now. 我将如何使用gsub替换说'text1', 'replacement1''text2', 'replacement2'以及为什么它不能像我现在设置的那样仅用于一次替换。

The data is stored as a string and grabbed from the db if that matters. 数据存储为字符串,并在重要时从数据库中获取。

Update 更新资料

Got it working. 得到它的工作。 forgot to add the equal sign on <%= on content.html_safe %> 忘记<%= on content.html_safe %>添加等号

still got the problem of having 2 gsub changes on the one string here is what I have which doesnt change any coding 仍然有一个字符串上有2 gsub更改的问题,这是我所拥有的,不会更改任何编码

 <% template = Liquid::Template.parse(@category.template)  %>

 <% render = template.render(@keys_values_hash) %>

  <%  
  replacements = [ ['data-imgslap=', 'src='], [' src="http://i.imgur.com/bEDR9dc.png"', ''] ]
  replacements.each {|replacement| render.gsub(replacement[0], replacement[1])}
  %>

 <%=  render.html_safe %>

Got this from another question on stackoverflow but it doesn't work for me. 这是从另一个关于stackoverflow的问题得到的,但对我而言不起作用。

Generally, don't use multi-line statements in ERB. 通常,不要在ERB中使用多行语句。 Make it two lines. 使它成为两行。 And use gsub! 并使用gsub! to change the render object. 更改render对象。

<% replacements = [ ['data-imgslap=', 'src='], ['src="http://i.imgur.com/bEDR9dc.png"', ''] ] %>
<% replacements.each {|replacement| render.gsub!(replacement[0], replacement[1])} %> 
<%=  render.html_safe %>

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

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