0

是否可以将隐藏字段添加到所有表单标签?我正在尝试通过以下方式进行操作:

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

但是服务器显示错误:

ActionView::Template::Error (Could not concatenate to the buffer because it is not html safe.):

我该怎么做?

4

2 回答 2

3

extra_tags_for_form重新定义用于添加 、 和隐藏字段的方法_method可能utf8authenticity_token简单。像这样的东西可以工作:

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

由于此建议涉及重新定义私有方法,因此您需要确保在升级 Rails 时仔细测试它。

于 2012-09-28T16:10:17.143 回答
1

尝试

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!使用 HTML 不安全性污染您的字符串。

于 2012-09-28T15:46:11.273 回答