Adding Google Fonts to a Drupal 8 theme

Some fonts on a web page

This took a bit more work to figure out than in Drupal 7! Bear in mind, this example is for installing a theme-wide (every page) font. There's references at the bottom where you might find further information on other methods.

Here's the old way of inserting Google Fonts (for every page using this theme):

function MYTHEME_preprocess_html(&$variables) {
  // this function is deprecated in D8 because, caching, I think
  drupal_add_css('//fonts.googleapis.com/css?family=Oxygen:300', array('group' => CSS_THEME));
}

In Drupal 8, however, we have to use the libraries method, which is "a bit" more involved. Firstly, we need to add a library to our theme.info.yml (see last two lines). Here, I've made a subtheme of Bartik to implement the feature against. Side note: the base theme name is not capitalised. This didn't work when I tried it, but is ok all lower case. Seems a bizarre thing, when the original theme is declared like name: Bartik but there you go.

name: Blah
description: It's a theme
type: theme
base theme: bartik
core: 8.x
libraries:
  - themeName/fonts

Then we need to create the library file. For whatever reason, the library is defined as themeName/libraryName in the .info.yml. The library file is called themeName.libraries.yml. The library file opens with a declaration of libraryName:

fonts:
  license:
    name: SIL Open Font License, 1.1
    url: http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL
  css:
    theme:
      //fonts.googleapis.com/css?family=Oxygen:300: { type: external }
      css/myStyles.css: {}

This YML file actually works fine without the license section, but it would be a bit poor to not even attempt to honour it... NB The font url has had the http: removed so that it is agnostic to secure-or-not connections at runtime.

If all that has worked, you should be able to view source on your site and see a comforting line of code like
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Oxygen:300" media="all" />
All that remains is to implement the font in your CSS by inserting a rule in the myStyles.css file in the css folder, like:

font-family: 'Oxygen', sans-serif;

References

Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme - https://www.drupal.org/theme-guide/8/assets
Defining a theme with an .info.yml file - https://www.drupal.org/node/2349827
Creating a Drupal 8 sub-theme - https://www.drupal.org/node/2165673

Blog Tags: DrupalCSSPlanetThemes

Add new comment