简体   繁体   English

防止rails将特殊字符转换为HTML实体

[英]Prevent rails from converting special characters to HTML entities

I'm using the following helper function, but it seems to convert all the special characters in my JavaScript statement to HTML entities, rendering it useless and broken. 我正在使用以下帮助函数,但它似乎将我的JavaScript语句中的所有特殊字符转换为HTML实体,使其无用且破坏。 Any suggestions? 有什么建议么?

 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 + "_fields", :f => builder)
    end
    link_to_function(name, h("add_fields(this, \"#{association}\", \"#{escape_javascript(fields)}\")"))
  end

The above generates a link like this (notice the conversions to $amp; - " etc: 上面会生成这样的链接(请注意转换为$amp; - "等:

<a href="#" onclick="add_fields(this, &amp;quot;skills&amp;quot;, &amp;quot;&amp;lt;label for=\&amp;quot;user_skills_attributes_new_skills_name\&amp;quot;&amp;gt;Skill&amp;lt;\/label&amp;gt;\n&amp;lt;input data-autocomplete=\&amp;quot;/users/autocomplete_skills_vocab_name\&amp;quot; id=\&amp;quot;user_skills_attributes_new_skills_name\&amp;quot; name=\&amp;quot;user[skills_attributes][new_skills][name]\&amp;quot; size=\&amp;quot;30\&amp;quot; type=\&amp;quot;text\&amp;quot; /&amp;gt;&amp;lt;br /&amp;gt;\n&amp;lt;input id=\&amp;quot;user_skills_attributes_new_skills__destroy\&amp;quot; name=\&amp;quot;user[skills_attributes][new_skills][_destroy]\&amp;quot; type=\&amp;quot;hidden\&amp;quot; value=\&amp;quot;false\&amp;quot; /&amp;gt;&amp;lt;a href=\&amp;quot;#\&amp;quot; onclick=\&amp;quot;remove_fields(this); return false;\&amp;quot;&amp;gt;remove&amp;lt;\/a&amp;gt;&amp;quot;); return false;">Add a Skill</a>

EDIT/ 编辑/

Figured it out -- For Rails 3 remove h() 想出来 - 对于Rails 3删除h()

In Rails 2, output by default was not escaped. 在Rails 2中,默认输出未被转义。 The h() method does this. h()方法执行此操作。 In Rails 2 views, you often see the following: 在Rails 2视图中,您经常会看到以下内容:

<%=h @object.field %>

However, in Rails 3 output is now escaped by default. 但是,在Rails 3中,输出现在默认是转义的。 You no longer need the h() method. 您不再需要h()方法。 In order to get unescaped output you have to use the raw method. 为了获得非转义输出,您必须使用原始方法。

More information is available here: http://railscasts.com/episodes/204-xss-protection-in-rails-3 有关更多信息,请访问: http//railscasts.com/episodes/204-xss-protection-in-rails-3

So basically in your case you were looking at Rails 2 code and the removal of the h() is needed to update it for Rails 3. 因此,基本上在你的情况下,你正在查看Rails 2代码,并且需要删除h()来更新Rails 3。

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

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