A note from the authors: Some of the information and instructions in this book are now out of date because of changes to Hugo and the blogdown package. If you have suggestions for improving this book, please file an issue in our GitHub repository. Thanks for your patience while we work to update the book, and please stay tuned for the revised version!

In the meantime, you can find an introduction to the changes and new features in the v1.0 release blog post and this "Up & running with blogdown in 2021" blog post.

— Yihui, Amber, & Alison

2.6 Custom layouts

您很可能想要自定义主题,除非您设计了它。最直接的方法是直接在主题中进行更改,9 但问题是 Hugo 主题可能会被其原作者不断更新以进行改进或错误修复。类似于 “you break it, you buy it” 的政策(the Pottery Barn rule),一旦你接触了别人的源代码,你将负责其未来的维护,而原作者不应对你所做的更改负责在你身边。这意味着将该主题的未来更新拉到您的网站可能并不容易(您必须仔细阅读更改并确保它们不会与您的更改冲突),但如果您对主题的当前状态完全满意并且不想以后更新,直接修改主题文件就可以了。

意识到用户可以自定义主题的主题作者通常会提供两种方法:一种是在 config.toml 中提供选项,以便您可以在不接触模板文件的情况下更改这些选项;另一种是在主题中的 layouts/ 下留下一些轻量级模板文件,这样你就可以覆盖它们而无需触及核心模板文件。以 XMin 主题为例:

我在主题中的 layouts/partials/ 下有两个空的 HTML 文件 head_custom.htmlfoot_custom.html。前者将添加到页面的 <head></head> 内,例如,您可以通过 <link> 加载 JavaScript 库或包含 CSS 样式表。后者将添加在页面页脚之前,例如,您可以加载其他 JavaScript 库或嵌入 Disqus comments。

自定义这两个文件的方式不是直接在主题文件夹中编辑它们,而是在网站根目录下创建一个目录 layouts/partials/,例如,您的目录结构可能如下所示:

your-website/
├── config.toml
├── ...
├── themes/
   └── hugo-xmin/
       ├── ...
       └── layouts/
           ├── ...
           └── partials
               ├── foot_custom.html
               ├── footer.html
               ├── head_custom.html
               └── header.html
└── layouts
    └── partials
        ├── foot_custom.html
        └── head_custom.html

根目录下的 layouts/ 下的所有文件将覆盖 themes/hugo-xmin/layouts/ 下具有相同相对路径的文件,例如文件 layouts/partials/foot_custom.html,如果提供,将覆盖 themes/hugo-xmin/layouts/partials/foot_custom.html。这意味着您只需要在 layouts/ 下创建和维护最多两个文件,而不是在 themes/ 下维护所有文件。请注意,此覆盖机制适用于 layouts/ 下的所有文件,并且不限 partials/ 目录。它还适用于您实际用于网站的任何 Hugo 主题,并且不限于 hugo-xmin


  1. 如果您是 Web 开发新手,请小心更改主题内的内容。颜色和字体大小等细微更改可以在主题的 CSS 文件中找到,并且可以简单地进行更改,而破坏主题功能的风险最小。↩︎