简体   繁体   中英

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

 <% 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

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.

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 %>

still got the problem of having 2 gsub changes on the one string here is what I have which doesnt change any coding

 <% 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.

Generally, don't use multi-line statements in ERB. Make it two lines. And use gsub! to change the render object.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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