Custom Fonts in Ruby on Rails 7

In this post, we will discuss how we can import custom fonts into a Rails 7 application using the asset pipeline. We will use Rails 7.0.3 and Ruby 3.1.2.

Let's say we want to use the Poppins font for our new Rails app. We want the regular weight for body text and the bold weight for headings.

First, we go to the Poppins page on Google fonts, download the font family, and unzip the downloaded file.

Where do we put these font files? In Rails, we can put pipeline assets into three folders: app/assets/, lib/assets/, and vendor/assets/. Since the font files we want to use are provided by a third party, we will put them in the vendor/assets/ folder. So, go ahead and create a sub-folder called assets in the vendor/ folder. Here, we'll create another sub-folder called fonts. In this sub-folder, we'll put the Poppins-Regular.ttf and Poppins-Bold.ttf files that we said we need for our app.

We can now refer to these files in our style sheets as they are in the search path. You can check this into the rails console by calling Rails.application.config.assets.paths.

We can refer to these fonts by using the font-face rule as follows:

 @font-face {
 font-family: 'Poppins';
 src: url('Poppins-Regular.ttf'),
      url('Poppins-Bold.ttf');
 font-display: swap;
}

 

Post last updated on August 4, 2022