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.3 Content

content/ 目录的结构可以是任意的。常见的结构是 content/ 根目录下有一些静态页面,以及一个包含博客文章的子目录 post/

├── _index.md
├── about.md
├── vitae.md
├── post/
   ├── 2017-01-01-foo.md
   ├── 2017-01-02-bar.md
   └── ...
└── ...

2.3.1 YAML metadata

每个页面都应以 YAML metadata 开头,指定标题、日期、作者、类别、标签等信息。根据您使用的特定 Hugo 主题和模板,其中一些字段可能是可选的。

在所有 YAML 字段中,我们希望引起您的注意:

  • draft: 您可以通过在其 YAML metadata 中设置 draft: true 将文档标记为草稿。如果网站是通过 blogdown::build_site()blogdown::hugo_build() 构建的,则不会呈现草稿帖子,但会在本地预览模式下呈现(请参阅 Section D.3)。

  • publishdate: 您可以指定发布帖子的未来日期。与草稿帖子类似,未来的帖子仅以本地预览模式呈现。

  • weight: 该字段可以采用数值来告诉 Hugo 排序时页面的顺序,例如,当您生成目录下所有页面的列表时,并且两个帖子具有相同的日期,您可以为它们分配不同的权重在列表中获取您想要的顺序。

  • slug: 作为 URL 尾部的字符串。当您为永久 URL 定义自定义规则时,它特别有用(请参阅 Section 2.2.2)。

2.3.2 Body

正如我们在 Section 1.6 中提到的,您的帖子可以用 R Markdown 或普通 Markdown 编写。当您编写帖子正文时,请注意两种格式之间的语法差异。

2.3.3 Shortcode

除了所有 Markdown 功能之外,Hugo 还提供了一个名为 “shortcodes” 的有用功能。您可以在帖子正文中使用 shortcode。当 Hugo 渲染帖子时,它可以根据您传递给 shortcode 的参数自动生成 HTML 片段。这很方便,因为您不必在帖子中键入或嵌入大量 HTML 代码。例如,Hugo 有一个内置的 shortcode,用于嵌入 Twitter 卡片。通常,这是在页面上嵌入 Twitter 卡(Figure 2.2)的方式:

<blockquote class="twitter-tweet">
  <p lang="en" dir="ltr">Anyone know of an R package for
    interfacing with Alexa Skills?
    <a href="https://twitter.com/thosjleeper">@thosjleeper</a>
    <a href="https://twitter.com/xieyihui">@xieyihui</a>
    <a href="https://twitter.com/drob">@drob</a>
    <a href="https://twitter.com/JennyBryan">@JennyBryan</a>
    <a href="https://twitter.com/HoloMarkeD">@HoloMarkeD</a> ?
  </p>
  &mdash; Jeff Leek (@jtleek)
  <a href="https://twitter.com/jtleek/status/852205086956818432">
    April 12, 2017
  </a>
</blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8">
</script>
A tweet by Jeff Leek.

FIGURE 2.2: A tweet by Jeff Leek.

如果您使用 shortcode,您在 Markdown 源文档中只需要:

{{< tweet user="jtleek", id="852205086956818432" >}}

基本上,您只需将推文的用户名和 ID 传递给名为 tweet 的 shortcode。6 Hugo 将自动获取推文并为您呈现 HTML 片段。有关 shortcodes 的更多信息,请参阅 https://gohugo.io/extras/shortcodes/

Shortcodes 应该仅适用于纯 Markdown 文档。要在 R Markdown 中使用 shortcodes 而不是普通 Markdown,您必须调用函数 blogdown::shortcode(),例如,

```{r echo=FALSE}
blogdown::shortcode(
  "tweet", user = "jtleek", id = "852205086956818432"
)
```

  1. Hugo v0.89.0 之前,只需要传递 ID 即可。由于 Twitter 自 2021 年底开始要求用户名,这意味着如果您想使用 Twitter shortcode,则必须使用 Hugo >= 0.89.0 并提供用户名。不幸的是,对于旧版本的 Hugo,shortcode 将被破坏。↩︎