Railsでbootstrap-iconsを簡単に使う


rails(webpacker)でbootstrap-iconsを使う方法

現時点ではv1.0.0-alpha5が最新なので今後変わると思います。

npm
npm install bootstrap-icons

yarn
yarn add bootstrap-icons

次に app/helpers/application_helper.rb に以下を追記します。

module ApplicationHelper
  ...
  # 追加
  def icon(icon, options = {})
    file = File.read("node_modules/bootstrap-icons/icons/#{icon}.svg")
    doc = Nokogiri::HTML::DocumentFragment.parse file
    svg = doc.at_css 'svg'
    if options[:class].present?
      svg['class'] += " " + options[:class]
    end
      doc.to_html.html_safe
  end
end

viewはslimを使用しているので

=icon("hdd", class: "text-gray")

で表示されます。