具有Font-Awesome的Rails简单表单输入

时间:2019-03-01 13:26:35

标签: simple-form ruby-on-rails-5.2

我想在水平的simple_form中使用图标代替文本作为标签。但是,我无法将文本与图标分开

= simple_form_for @user, html: { class: 'form-horizontal' }, wrapper: :horizontal_form do |f|

  # shows 'username' label only
  = f.input :username

  # shows icon with 'username'
  = f.input :username, label_html: {class: "fas fa-user"}

  # shows nothing
  = f.input :username, label_html: {class: "fas fa-user"}, label: false

4 个答案:

答案 0 :(得分:0)

您可以使用wrapper_html选项:

= f.input :username, label: false, wrapper_html: { class: 'fa fa-user' }

您可能必须添加一些CSS,以使其看起来像您想要的样子。例如,要将图标放置在与输入不同的行上,我必须在该图标上添加display: block

Font Awesome Icon

答案 1 :(得分:0)

wrapper_html:label_html:很复杂,所以我只是手动完成

.row
  .col-3
    .text-right
      i.fas.fa-user
  .col-9
    = f.input_field :username, label: false, class: 'form-control'

答案 2 :(得分:0)

对于那些想做同样事情的人,有一种更简单/更干净的方法:

= f.label :username, label: ('<i class="fas fa-user"></i>').html_safe
= f.text_field :username

还可以使用I18n本地化文件:

(en.yml)
username: '<i class="fas fa-user"></i>'

然后

= f.label :name, label: t(:username).html_safe
= f.text_field :username

使用simple_form(4.1.0)

希望此帮助。

答案 3 :(得分:0)

我刚刚在我自己的项目中实现了这个功能。有一个非常简单的解决方案。

首先,我创建了一个用于输出 fontawesome 图标的助手。在app/helpers/font_awesome_helper.rb

module FontAwesomeHelper
  def fa_icon(icon, style: :regular)
    content_tag(:i, "", class: [icon_style_class(style), icon_class(icon)].join(" "))
  end

  private
    def icon_class(icon)
      "fa-#{icon}"
    end

    def icon_style_class(style)
      case style
      when :light, :l
        "fal"
      when :regular, :r
        "far"
      when :solid, :s
        "fas"
      when :duotone, :duo, :d
        "fad"
      else
        "fa"
      end
    end
end

您可以进一步扩展它以支持反转图标颜色、水平翻转等。

最后,您可以在简单格式的输入中使用 fa_icon 助手:

= f.input :username, label: fa_icon("user", style: :solid)