以这种方式设置错误消息HTML视图?
-
25-10-2019 - |
题
我在用着 Twitter-Bootstrap 并希望生成正确的HTML以显示错误视图在主站点上的操作方式,即:
上述字段的HTML是:
<div class="control-group error">
<label for="inputError" class="control-label">Input with error</label>
<div class="controls">
<input type="text" id="inputError">
</div>
</div>
注意:我删除了 Please correct the error, <span>
, ,我只想要输入字段和标签。
如果我要以我的注册页面为例 email
字段,将是:
<div class="control-group">
<label for="user_email" class="control-label">Email*</label>
<div class="controls">
<input type="email" value="" name="user[email]" id="user_email" class="span3">
</div>
</div>
我该怎么做才能使它像前者一样的功能?
解决方案
不要重新发明轮子。利用 简单的模式. 。当前版本的GEM允许您执行以下操作:
rails generate simple_form:install --bootstrap
因此,您可以使用simple_form助手。他们将为您生成正确的事物。
其他提示
我刚刚遇到了这个问题,并已对Bootstrap CSS进行了简单的修改。
我通常的字段代码是:
<div class="control-group">
<%= f.label :fieldname, t('models.model.fieldname'), :class => "control-label" %>
<div class="controls">
<%= f.text_field :fieldname, :class => 'input-large' %>
</div>
</div>
因为我正在使用 f.label
和 f.text_field
标签和输入都用Divs封装 field_with_errors
班级(如尼古拉斯所述),使结果html:
<div class="control-group">
<div class="field_with_errors"><label class="control-label" for="model_fieldname">Field name</label></div>
<div class="controls">
<div class="field_with_errors"><input class="input-large" id="model_fieldname" name="model[fieldname]" size="30" type="text" value=""></div>
</div>
</div>
使这些外观与Bootstrap相同 <div class="control-group error">
样式我添加了一些额外的选择器 bootstrap.css
. 。我发现所有引用 .control-group.error ...
并与 .control-group .field_with_errors ...
. 。所以我最终得到了这种事情:
.control-group.error > label,
.control-group.error .help-block,
.control-group.error .help-inline,
.control-group .field_with_errors > label,
.control-group .field_with_errors .help-block,
.control-group .field_with_errors .help-inline {
color: #b94a48;
}
这可能不是最优雅的轨道方式,但对我来说,它似乎比更多的依赖宝石或覆盖错误处理要容易得多。是的,每次更新Bootstrap时,您都必须进行相同的更改,但是它们相当简单,并且您可能会自动进行补丁文件。
Rails会自动生成一类 field_with_errors
出现错误消息时。 Div用错误包裹元素。为了自定义,您可以将此行添加到 application.rb
:
config.action_view.field_error_proc = Proc.new { |html_tag, instance| %Q(<div class="field_with_errors">#{html_tag}</div>).html_safe }
这是默认值,因此,为了获得与Twitter Bootstrap相同的结构,您可以使用它。
html_tag
是该领域的占位符,例如 <input name="model[attribute]" size="30" type="text" value="">
您可以将其包裹在另一个Div中,还可以添加一个跨度,说“请更正错误”。
更多信息: http://guides.rubyonrails.org/configuring.html - 项目3.9