Twitter Bootstrap 3 + Rails 4: Fix issue which prevents fonts from loading

Normally, there are two basic ways to integrate Twitter Bootstrap into your Rails application

  1. Install a twitter boostrap gem and do a little configuration
  2. Manually copy Bootstrap JS + CSS + Fonts into your app

The first option is quite easy and many people choose to follow this one. There are also many gems available https://www.ruby-toolbox.com/search?utf8=✓&q=bootstrap. However, the disadvantage of this method is that it is not possible to upgrade Bootstrap library in your app whenever there is new Bootstrap version, because we have to wait for the gem owner to release new version of that gem. In addition, if you want to debug some lines of code in Bootstrap library, it is also very hard because the JS and CSS are in the gem location and not visible to you.

Having said that, there will definitely some developers choose the second option: manually copy Bootstrap assets to application source code (I am one of them). I believe that this is also not too difficult as the downloaded package from Boostrap is divided into three separate folders:

  • fonts
  • javascript
  • css

Just put bootstrap JS into vendor/assets/javascripts, put CSS into vendor/assets/stylesheet and put fonts folder at the same level with stylesheets and javascripts folders inside vendor. So, your project would look like this:

  • app
  • ...
  • vendor
    • assets
      • fonts
        • All glyphicon font files
      • javascripts
        • bootstrap.min.js
      • stylesheets
        • bootstrap.min.css

As you notice, we put all glyphicon font files in fonts folder and assume that these fonts would be loaded properly on browsers. However, if you run your project and start using a class like the following

<a class="glyphicon glyphicon-plus"></a>

You will see perhaps a square box instead of the icon. And if you open Developer tool in your browsers, you probably see the following error messages

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3000/fonts/glyphicons-halflings-regular.woff

Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:3000/fonts/glyphicons-halflings-regular.ttf

The reason for this is because the way our Rails application serve static assets is slightly different from what we normally see in traditional HTML app. All assets in fonts, javascripts and stylesheets folder will be served as /assets path from the browsers. It means that the correct URL for your fonts should be like this:

http://localhost:3000/assets/glyphicons-halflings-regular.woff

So, to fix this issue, you need to change the path to fonts in Boostrap CSS file. Open this file and perform a Find & Replace on bootstrap.min.css (or bootstrap.css)

Search: ../fonts/
Replace With: /assets/

And that's it. You will feel happy to continue using Bootstrap without relying on any gem.