0

So I'm trying to get a remove link next to the caption in an emails form. However, my rails voodoo is clearly very weak. It escapes the HTML and I can't figure out how to get it to not. Any hints?

= f.input :email, :label => "Email " + link_to_remove_fields("[x]", f)

[edit] oh and yes, this does the same thing:

= f.input :email, :label => "Email #{link_to_remove_fields("[x]", f)}"

and here's my helper method...

def link_to_add_fields(name, f, association)
    new_object = f.object.class.reflect_on_association(association).klass.new
    fields = f.fields_for(association, new_object, :child_index => "new_#{association}") do |builder|
      render(association.to_s.singularize + "_fields", :f => builder)
    end
    link_to_function(name, "add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")")
  end
Brian Hicks
  • 6,213
  • 8
  • 51
  • 77

3 Answers3

4

This isn't too hard to fix. Rails will escape everything by default. In order to prevent that you can use the method html_safe on any string. This would fix your issue.

= f.input :email, :label => "Email " + link_to_remove_fields("[x]", f).html_safe

or

= f.input :email, :label => "Email #{link_to_remove_fields("[x]", f).html_safe}"

Remember not to put it at the end of the entire tokenized string, or it won't work. For instance, this won't work.

= f.input :email, :label => "Email #{link_to_remove_fields("[x]", f)}".html_safe

Hope this helps you out. =)

quest
  • 776
  • 5
  • 14
  • That doesn't work for me... I think it's my helper method. I've put the code in my question, where should I put html_safe in it? – Brian Hicks Sep 26 '10 at 00:00
  • If you generate strings in your helpers, you also need to use .html_safe on those, or they will be already escaped when they get to your view. You seem to call other helpers within that block, can you post them? – quest Sep 26 '10 at 00:13
  • They're just formtastic calls. If I escape any of them it makes a lot of errors in other portions of my code for some reason. – Brian Hicks Sep 26 '10 at 02:39
  • Well if you can't find a place in the helper to fix it, you could use the htmlentities gem to decode the entities. The library is extremely easy to use, and can decode anything you throw at it. Check out http://htmlentities.rubyforge.org – quest Sep 27 '10 at 01:40
  • or try `f.input(:email, :label => "...").html_safe` – PeterWong Sep 27 '10 at 09:56
1

I had the same issue as this, I fixed it by using the following in my helper:

link_to_function(name, "add_fields(this, '#{association}', \'#{escape_javascript(fields)}\')")

One thing to note, when I tried this in a Rails 3.1 app I had to restart the server before changes in the helper were picked up. This may or may not be true for earlier versions but worth keeping in mind.

Kevin Ansfield
  • 2,343
  • 1
  • 19
  • 20
0

Try this:

require 'cgi'

unescaped = CGI.unescapeHTML(string)
dombesz
  • 7,890
  • 5
  • 38
  • 47