Rails: add field to all forms
-
04-07-2021 - |
题
Is it possible to add hidden field to all form tags? I'm trying to do it in following way:
module ActionView::Helpers::FormTagHelper
def form_tag(url_for_options = {}, options = {}, &block)
html_options = html_options_for_form(url_for_options, options)
if block_given?
f = form_tag_in_block(html_options, &block)
else
f = form_tag_html(html_options)
end
hidden_f = ActiveSupport::SafeBuffer.new "<input name='n' type='hidden' value='v' /><\/form>"
f.gsub!(/<\/form>/, hidden_f)
f
end
end
But server shows the error:
ActionView::Template::Error (Could not concatenate to the buffer because it is not html safe.):
How should i do it?
解决方案
It might be simpler to redefine the extra_tags_for_form
method, which is used to add the _method
, utf8
, and authenticity_token
hidden fields. Something like this could work:
module ActionView::Helpers::FormTagHelper
alias_method :orig_extra_tags_for_form, :extra_tags_for_form
def extra_tags_for_form(html_options)
orig_tags = orig_extra_tags_for_form(html_options)
orig_tags << "<input name='n' type='hidden' value='v' /><\/form>".html_safe
end
end
Since this advice involves redefining a private method, you will need to be sure to test it carefully any time you upgrade Rails.
其他提示
Try with
module ActionView::Helpers::FormTagHelper
def form_tag(url_for_options = {}, options = {}, &block)
html_options = html_options_for_form(url_for_options, options)
if block_given?
f = form_tag_in_block(html_options, &block)
else
f = form_tag_html(html_options)
end
hidden_f = ActiveSupport::SafeBuffer.new "<input name='n' type='hidden' value='v' /><\/form>"
f.gsub!(/<\/form>/, hidden_f)
f.html_safe
end
end
gsub!
taints your string with HTML unsafeness.
不隶属于 StackOverflow