hugo 是 go 语言写的一个静态网站生成器,它的主要特点是快速、简单、灵活。在使用 hugo 时,我们可能需要在网站中添加谷歌字体,这篇文章就来介绍如何在 hugo 上添加谷歌字体。
我用的是 PaperMod
的主题,可以通过修改主题里的 html 文件来实现,接下来按照以下步骤来添加谷歌字体。
谷歌字体
我们在谷歌官方的字体库中找到我们需要的字体,比如 Roboto
字体,点击右上角的 View Selected families
图标,然后点击 Get embed code
按钮。

然后进入到 Embed Code
页面,我们可以看到有两种方式来添加字体,一种是通过 link
引入,另一种是通过 @import
标签引入,这里我们选择 link
标签引入。我们拷贝 link
标签的代码。

修改主题的 html 文件
接下来我们找到 hugo 的主题文件夹,在 themes/PaperMod/layouts/partials/extend_head.html
文件以下代码。如果是其他主题,找到对应的 head.html 文件添加即可。
1 2 3 4 5 6
| <link rel="preconnect" href="https://fonts.googleapis.com" /> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin /> <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet" />
|
然后在 themes\PaperMod\assets\css\extended\blank.css
文件中添加以下代码。如果是其他主题,找到类似的应用于全局的 css 文件添加即可。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| .roboto-thin { font-family: "Roboto", system-ui; font-weight: 100; font-style: normal; }
.roboto-light { font-family: "Roboto", system-ui; font-weight: 300; font-style: normal; }
.roboto-regular { font-family: "Roboto", system-ui; font-weight: 400; font-style: normal; }
.roboto-medium { font-family: "Roboto", system-ui; font-weight: 500; font-style: normal; }
.roboto-bold { font-family: "Roboto", system-ui; font-weight: 700; font-style: normal; }
.roboto-black { font-family: "Roboto", system-ui; font-weight: 900; font-style: normal; }
.roboto-thin-italic { font-family: "Roboto", system-ui; font-weight: 100; font-style: italic; }
.roboto-light-italic { font-family: "Roboto", system-ui; font-weight: 300; font-style: italic; }
.roboto-regular-italic { font-family: "Roboto", system-ui; font-weight: 400; font-style: italic; }
.roboto-medium-italic { font-family: "Roboto", system-ui; font-weight: 500; font-style: italic; }
.roboto-bold-italic { font-family: "Roboto", system-ui; font-weight: 700; font-style: italic; }
.roboto-black-italic { font-family: "Roboto", system-ui; font-weight: 900; font-style: italic; }
|
使用谷歌字体
最后在 body 标签声明 font-family
为 Roboto
字体即可。
1 2 3 4 5 6
| body { font-family: "Roboto", sans-serif; font-optical-sizing: auto; line-height: 1.5; margin: 0; }
|