Rails Simple Form input with Font-Awesome

我的梦境 提交于 2021-01-29 08:17:06

问题


I want to use icons instead of text for labels in a horizontal simple_form. However, I am unable to separate the text from the icons

= 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

回答1:


You can use the wrapper_html option:

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

You will probably have to add some css to make it look the way you want. For example, to get the icon on a different line than the input, I had to add display: block to the icon.




回答2:


wrapper_html: and label_html: were complicated, so I just did it manually

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



回答3:


For those who want to do the same, there is a simpler/cleaner way :

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

Also work with I18n localization file :

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

then

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

Using simple_form (4.1.0)

Hope this help.




回答4:


I've just implemented this very thing on my own project. There was a really simple solution.

First, I created a helper for outputting fontawesome icons. In 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

You can extend this further to support inverting icon colours, flipping horizontally, etc.

Finally, you can use your fa_icon helper in your simple-form input:

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


来源:https://stackoverflow.com/questions/54945633/rails-simple-form-input-with-font-awesome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!