Using Bootstrap Icons in Rails 6 with Webpacker
Font awesome is good and font awesome rails gem neatly integrates with Rails framework, but I think it uses Sprockets which is going out of fashion :(. As a community we are embracing webpacker, I wish we embraced Opal and ditched Javascript completely, but it’s not happening. Anyway…
Font awesome is okay, but their premium icons hide behind paywall and they are not as committed to free software as Booststrap guys I think. Font awesome needs money, they are into that model. The law of software development says that if you are offering a service, there is always a person to outsmart you. Welcome Bootstraop icons https://icons.getbootstrap.com/
Now how to use it? First add the necessary dependencies using yarn
$ yarn add bootstrap-icon
Now create a file called app/helpers/bootstrap_icons_helper.rb
, in it add this code
module BootstrapIconsHelper
# refer https://icons.getbootstrap.com/
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
Now in the app anywhere use this to add an icon
<%= icon("alert-circle", class: "text-success") %>
To refer the names of icons goto https://icons.getbootstrap.com/.