新手问题 请问 ActionView::Base.field_error_proc 下的 html 操作

QueXuQ · 2012年12月07日 · 最后由 QueXuQ 回复于 2012年12月11日 · 2413 次阅读
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
  unless html_tag =~ /^<label/
    %{<p class="field_with_errors">#{html_tag}</p><p class="error-message"><label for="#{instance.send(:tag_id)}" class="message"><s>#{instance.error_message.first}</s></label></p>}.html_safe
  else
    %{<div class="field_with_errors">#{html_tag}</div>}.html_safe
  end
end

如果向上面的显示错误的方式,生成的 html 会像下面那样

inpu输入框
error错误

如果我的 input 本来有一个 p 包着的,如:

p
  inpu输入框

而我不希望 error 也生成在 p 里,但是#{html_tag}只是一个输入框而已,请问怎么获取他外面的那个 p,而生成如下的界面呢?:

p
  inpu输入框
p
  error错误

你要自己改就要看源码 hack 了哦,否则,建议使用 simple_form,然后设定自己的 wrapper。

config.wrappers :custom do |b|
  b.wrapper :tag => "p" do |p|
    p.use :input
  end
  ba.use :error,  :wrap_with => { :tag => 'p' }
end

不懂的看 github wiki 哦

#1 楼 @yakjuly 恩。谢谢。一开始想着因为就是一个 form 而已,所以不想使用 simple_form,没想到不用的话那么麻烦。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号