How to add google font into magento2

S.S.Niranga
2 min readAug 31, 2020

--

The Error

I needed to add font-family “Lato” into my theme and I decided to inject the CSS file adding below code to my Magento theme using default_head_blocks.xml

Create this file in your theme if it doesn't exist.

VENDOR\YOUR_THEME\Magento_Theme\layout\default_head_blocks.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700;900&display=swap" rel="stylesheet">

</head>
</page>

However, after the above change, I received the below error on the page,

1 exception(s):
Exception #0 (Magento\Framework\Config\Dom\ValidationException): Theme layout update file 'VENDOR/YOUR_THEME/Magento_Theme/layout/default_head_blocks.xml' is not valid.
EntityRef: expecting ';'
Line: 13
Opening and ending tag mismatch: link line 13 and head
Line: 14
Opening and ending tag mismatch: head line 10 and page
Line: 15
Premature end of data in tag page line 8
Line: 16

Exception #0 (Magento\Framework\Config\Dom\ValidationException): Theme layout update file '/var/www/html/ext/atlas/magento2_theme-frontend-atlas/Magento_Theme/layout/default_head_blocks.xml' is not valid.
EntityRef: expecting ';'
Line: 13
Opening and ending tag mismatch: link line 13 and head
Line: 14
Opening and ending tag mismatch: head line 10 and page

It seems Magento is not happy with the link that googles provides and display above error when trying to read the default_head_blocks.xml

The solution is simple.

All you have to do is replace href tag to src and add a few extra tags to the embedded link.

From

<link href="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700;900&display=swap" rel="stylesheet">

To

<link src_type="url" type="text/css" src="https://fonts.googleapis.com/css2?family=Lato:wght@300;400;700;900&amp;display=swap" rel="stylesheet" />

That’s all !!!!

--

--

S.S.Niranga

Magento Tech Lead @Biopak. Ecommerce Consultant @bodyscience. (MSc, Author, Magento Certified Developer, MCTS, Scrum Master)