Simple Form 使用教程

Simple Form 使用教程

simple_formForms made easy for Rails! It's tied to a simple DSL, with no opinion on markup.项目地址:https://gitcode.com/gh_mirrors/si/simple_form

项目介绍

Simple Form 是一个为 Rails 应用程序设计的表单生成工具,旨在简化表单的创建过程。它提供了一个简洁的 DSL(领域特定语言),并且不强制任何特定的标记风格,使得开发者可以灵活地定制表单的外观和行为。

项目快速启动

安装 Simple Form

首先,将 Simple Form 添加到你的 Gemfile 中:

gem 'simple_form'

然后运行 bundle 安装:

bundle install

接下来,运行安装生成器:

rails generate simple_form:install

创建表单

在你的视图文件中,使用 Simple Form 创建表单:

<%= simple_form_for @user do |f| %>
  <%= f.input :username %>
  <%= f.input :password %>
  <%= f.button :submit %>
<% end %>

应用案例和最佳实践

自定义输入组件

Simple Form 允许你自定义输入组件。例如,创建一个自定义的日期选择器:

# app/inputs/date_picker_input.rb
class DatePickerInput < SimpleForm::Inputs::Base
  def input(wrapper_options)
    merged_input_options = merge_wrapper_options(input_html_options, wrapper_options)
    @builder.text_field(attribute_name, merged_input_options)
  end
end

然后在表单中使用这个自定义输入:

<%= simple_form_for @user do |f| %>
  <%= f.input :birthday, as: :date_picker %>
<% end %>

使用 Bootstrap 样式

Simple Form 可以与 Bootstrap 集成,提供美观的表单样式:

# config/initializers/simple_form_bootstrap.rb
SimpleForm.setup do |config|
  config.wrappers :bootstrap, tag: 'div', class: 'form-group', error_class: 'has-error' do |b|
    b.use :html5
    b.use :placeholder
    b.use :label
    b.wrapper tag: 'div', class: 'col-sm-10' do |ba|
      ba.use :input
      ba.use :error, wrap_with: { tag: 'span', class: 'help-block' }
      ba.use :hint,  wrap_with: { tag: 'p', class: 'help-block' }
    end
  end
end

典型生态项目

Active Storage

Simple Form 与 Active Storage 集成,可以轻松处理文件上传:

<%= simple_form_for @user do |f| %>
  <%= f.input :avatar, as: :file %>
<% end %>

CarrierWave

与 CarrierWave 集成,处理文件上传:

<%= simple_form_for @user do |f| %>
  <%= f.input :avatar, as: :file %>
<% end %>

Devise

Simple Form 与 Devise 集成,简化用户认证表单的创建:

<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
  <%= f.input :email, required: false, autofocus: true %>
  <%= f.input :password, required: false %>
  <%= f.input :remember_me, as: :boolean if devise_mapping.rememberable? %>
  <%= f.button :submit, "Log in" %>
<% end %>

通过这些集成,Simple Form 可以与多个流行的 Rails 生态项目无缝协作,提供强大的表单处理能力。

simple_formForms made easy for Rails! It's tied to a simple DSL, with no opinion on markup.项目地址:https://gitcode.com/gh_mirrors/si/simple_form

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

戴玫芹

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值