1
0

Rails7 Bootstrap slimのfile_fieldの見た目をアイコンにする

Posted at

This article shows how to change the appearance of slim's file_field to Bootstrap icon.

環境情報&前提条件

  • Ruby 3.2.1
  • Rails 7.0.0
  • Bootstrap 5.2.3
  • テンプレートエンジンとしてslimを使用

解決したい内容

  • formタグの中のfile_fieldの見た目を以下の①通常の見た目でなく、②アイコンの見た目にしたい

①通常の見た目
通常のfile_field.png

②アイコンの見た目(画像左のimageアイコンをクリックして画像添付としたい)
iconに変更したfile_field.png

  • Userモデルのimageカラムに画像を添付するケースを想定する。

解決手順

  • 以下のようにlabelの中にfile_fieldを内包させる。
  • file_field自体はstyle: "display: none"して非表示にする。
  • ※アイコン部分にはstyle="cursor: pointer"を設定して、アイコンにホバーした際にポインタとなるようにしています。必須ではありません。
<!-- パスやモデルは適宜置換してください。 -->
= form_with url: users_path, model: User.new, data: { turbo: false }, locale: true do |f|
  = f.label :image
    i.fs-3.bi-image.text-primary[style="cursor: pointer"]
    = f.file_field :image, style: "display: none"
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0