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.7 Static files

Hugo 渲染网站时,static/ 目录下的所有文件都会复制到 public/ 中。该目录通常用于存储静态 Web 资源,例如图像、CSS 和 JavaScript 文件。例如,可以使用 Markdown 语法 ![](/foo/bar.png) 将图像 static/foo/bar.png 嵌入到您的帖子中。10

通常主题有一个 static/ 文件夹,您可以使用与覆盖 layouts/ 文件相同的机制部分覆盖其文件,即 static/file 将覆盖 themes/theme-name/static/file。在 XMin 主题中,我有两个 CSS 文件 style.cssfonts.css。前者是主要样式表,后者是一个非常小的文件,仅用于定义字体。您可能想定义自己的字体,并且只能提供 static/css/fonts.css 来覆盖主题中的字体,例如,

body {
  font-family: "Comic Sans MS", cursive, sans-serif;
}
code {
  font-family: "Courier New", Courier, monospace;
}

对于 R Markdown 用户来说,static/ 目录的另一个重要应用是构建具有自定义输出格式的 Rmd 文档,即不使用 blogdown::html_page() 格式的 Rmd 文档(参见 Section 1.6)。例如,您可以从此目录下的 Rmd 文档生成 PDF 或演示文稿,这样 Hugo 就不会对其进行后期处理,而只是将其复制到 public/ 进行发布。要构建这些 Rmd 文件,您必须提供自定义构建脚本 R/build.R(请参阅 Section D.9)。您可以在此脚本中编写一行代码:

blogdown::build_dir("static")

函数 build_dir() 查找目录下的所有 Rmd 文件,并调用 rmarkdown::render() 将它们构建为 Rmd 文件的 YAML metadata 中指定的输出格式。如果您的 Rmd 文件不应通过简单的 rmarkdown::render() 调用来呈现,您可以自由提供自己的代码以在 R/build.R 中呈现它们。函数 build_dir() 中有一个内置的缓存机制:如果 Rmd 文件早于其输出文件,则不会编译该文件。如果您不希望出现此行为,可以强制每次重新编译所有 Rmd 文件:build_dir(force = TRUE)

我在 GitHub 存储库 yihui/blogdown-static, 中提供了一个最小的示例,您可以在 static/ 目录下找到两个 Rmd 示例。一个是基于 xaringan 包的 HTML5 演示文稿,另一个是基于 bookdown 的 PDF 文档。

由于 Hugo 的覆盖机制,您需要谨慎对待 static/ 下的任意文件。也就是说,static/ 下的所有内容都会被复制到 public/。您需要确保在 static/ 下渲染的文件不会与 Hugo 从 content/ 自动生成的文件冲突。例如,如果您同时有一个源文件 content/about.md 和一个 Rmd 文件 static/about/index.Rmd,则后者的 HTML 输出将覆盖前者(Hugo 和您都会生成一个输出文件具有相同的名称 public/about/index.html)。


  1. 图像的链接取决于您在 config.toml 中的 baseurl 设置。如果它不包含子路径,/foo/bar.png 将是图像的链接,否则你可能需要调整它,例如,对于 baseurl = "http://example.com/subpath/",链接图像应该是 /subpath/foo/bar.png↩︎