Creating a New Theme in Hugo

Introduction

本教程将展示如何在 Hugo 中创建一个简单的主题。我假设你熟悉 HTML、bash 命令行,并且你很熟悉使用 Markdown 来格式化内容。我将解释 Hugo 如何使用模板以及如何组织模板以创建主题。我不会介绍如何使用 CSS 来设置主题样式。

打算深入理解 Hugo 如何工作的话,这是一篇非常好的文档。

我们将从创建一个具有非常基本模板的新站点开始。然后,我们将添加一些页面和帖子。通过微小的变化,你将能够创建许多不同类型的网站。

在本教程中,输入的命令将以“$”提示符开头。输出将随之而来。以“#”开头的行是我为解释一个观点而添加的注释。当我显示文件更新时,最后一行的“:wq”表示保存文件。

Here’s an example:

## this is a comment
$ echo this is a command
this is a command

## edit the file
$ vi foo.md
---
date: "2014-09-28"
title: "creating a new theme"
---

bah and humbug
:wq

## show it
$ cat foo.md
---
date: "2014-09-28"
title: "creating a new theme"
---

bah and humbug
$

Some Definitions

在创建主题之前,需要了解一些概念。

Skins

皮肤(skin)是负责站点视觉风格(look and feel)的文件。CSS 控制颜色和字体,Javascript决定动作和反应。这也是 Hugo 用来将内容转换为 HTML 的规则,该网站将为访客提供服务。

创建皮肤有两种方法。最简单的方法是在 layouts/ 目录中进行创建。如果你这样做了,那么就不必额外去配置 Hugo 来识别它。Hugo 寻找规则和文件的第一个地方就是在 layouts/ 目录中,所以它总是会找到皮肤。

第二个选择是在 themes/ 目录的子目录中创建皮肤。如果这样做了,那么你必须告诉 Hugo 去哪里寻找皮肤。不过,这是额外的工作,为什么要费心去做呢?

layouts/ 中创建皮肤和在 themes/ 中创建皮肤之间的区别是非常微妙的。layouts/ 中的皮肤不能在没有更新模板和静态文件的情况下进行定制;而在 themes/ 中创建的皮肤是可以的,这让其他人更容易使用它。

The rest of this tutorial will call a skin created in the themes/ directory a theme.

注意,如果你愿意,可以使用本教程在 layouts/ 目录中创建一个皮肤。主要的区别是,不需要更新站点的配置文件来使用主题。

The Home Page

首页,或登陆页,是许多访问网站的人看到的第一页。它是网站根目录下的 index.html 文件。由于 Hugo 将文件写入 public/ 目录,所以我们的主页是 public/index.html

Site Configuration File

Hugo 运行时,将查找包含覆盖整个站点默认值的设置的配置文件。YAML、TOML 或 JSON。我更喜欢在配置文件中使用 YAML。如果您更喜欢使用 JSON 或 TOML,则需要翻译我的示例。你还需要更改文件的名称,因为 Hugo 使用扩展名来确定如何处理它。

Hugo 将 Markdown 文件翻译成 HTML。默认情况下,Hugo 希望

  • content/ 目录中找到 Markdown 内容文件
  • themes/ 目录中找到模板文件
  • public/ 目录中创建 HTML 文件 你可以通过在配置文件中指定备用位置来更改这一点。

Content

内容存储在包含两个部分(two sections)的文本文件中

  • 第一部分是 “front matter”,即内容的元信息
  • 第二部分包含将被转换为 HTML 的 Markdown 文本内容。

Front Matter

Front Matter 是关于内容的信息。与配置文件一样,它可以用 YAML、TOML 或 JSON 编写。与配置文件不同,Hugo 不使用文件的扩展名来了解格式。它寻找标志类型的标记。YAML 被 “---” 包围,TOML 被 “+++” 包围,JSON 被大括号包围。

Front Matter 中的信息首先被传递到模板,之后的内容再呈现为HTML。

Markdown

内容是用 Markdown 写的,这使得创建内容更容易。Hugo 通过运行 Markdown 引擎处理内容,创建 HTML 写入文件。

Template Files

Hugo 使用模板文件将内容呈现为 HTML。模板文件是内容和表示之间的桥梁。模板中的规则定义了发布什么内容、发布到哪里以及如何将其呈现给 HTML 文件。模板通过指定要使用的样式来指导表示。

有三种类型的模板:single 模板、list 模板和 partial 模板。每种类型都接受一些内容作为输入,并根据模板中的命令对其进行转换。

Hugo 使用其内容知识来查找用于呈现内容的模板文件。如果它不能找到与内容完全匹配的模板,它将从那里转移到上一个级别和搜索。它将继续这样做,直到它找到一个匹配的模板或没有模板可以尝试。如果它找不到模板,它将使用该站点的默认模板(layouts/)。

请注意,用户可以使用 front matter 来影响 Hugo 对模板的选择。

Single Template

A single template is used to render a single piece of content. For example, an article or post would be a single piece of content and use a single template.

List Template

A list template renders a group of related content. That could be a summary of recent postings or all articles in a category. List templates can contain multiple groups.

The homepage template is a special type of list template. Hugo assumes that the home page of your site will act as the portal for the rest of the content in the site.

Partial Template

部分(Partial)模板是可以包含在其他模板中的模板。必须使用 “Partial” template 命令 调用部分模板。它们在汇总常见行为时非常方便。例如,站点可能有一个所有页面都使用的横幅(banner)。就可以创建一个带有横幅的部分,而不是将横幅的文本复制到每个单独和列表模板中。这样,如果你决定改变横幅,只需要改变部分模板。

Create a New Site

Let’s use Hugo to create a new web site. I’m a Mac user, so I’ll create mine in my home directory, in the Sites folder. If you’re using Linux, you might have to create the folder first.

The “new site” command will create a skeleton of a site. It will give you the basic directory structure and a useable configuration file.

$ hugo new site _site --format yaml
$ cd _site
$ ls -l
total 8
drwxr-xr-x  3 liyan  wheel  96 Jun 12 13:28 archetypes
drwxr-xr-x  2 liyan  wheel  64 Jun 12 13:28 assets
drwxr-xr-x  2 liyan  wheel  64 Jun 12 13:28 content
drwxr-xr-x  2 liyan  wheel  64 Jun 12 13:28 data
-rw-r--r--  1 liyan  wheel  74 Jun 12 13:28 hugo.yaml
drwxr-xr-x  2 liyan  wheel  64 Jun 12 13:28 i18n
drwxr-xr-x  2 liyan  wheel  64 Jun 12 13:28 layouts
drwxr-xr-x  2 liyan  wheel  64 Jun 12 13:28 static
drwxr-xr-x  2 liyan  wheel  64 Jun 12 13:28 themes
$

Take a look in the content/ directory to confirm that it is empty.

The other directories (archetypes/, layouts/, and static/) are used when customizing a theme. That’s a topic for a different tutorial, so please ignore them for now.

Generate the HTML For the New Site

Running the hugo command with no options will read all the available content and generate the HTML files. It will also copy all static files (that’s everything that’s not content). Since we have an empty site, it won’t do much, but it will do it very quickly.

$ hugo --logLevel info
Start building sites …
hugo v0.126.3+extended darwin/amd64 BuildDate=2024-06-02T13:02:43Z VendorInfo=brew

INFO  build:  step process substep collect files 0 files_total 0 pages_total 0 resources_total 0 duration 106.829µs
INFO  build:  step process duration 158.408µs
INFO  static: syncing static files to / duration 198.757µs
INFO  build:  step assemble duration 270.923µs
WARN  found no layout file for "html" for kind "home": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.
WARN  found no layout file for "html" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.
INFO  build:  step render substep pages site en outputFormat html duration 883.92µs
INFO  build:  step render substep pages site en outputFormat rss duration 2.045369ms
INFO  build:  step render pages 4 content 0 duration 3.020519ms
INFO  build:  step postProcess duration 9.589µs
INFO  build:  duration 3.592496ms

                   | EN
-------------------+-----
  Pages            |  4
  Paginator pages  |  0
  Non-page files   |  0
  Static files     |  0
  Processed images |  0
  Aliases          |  0
  Cleaned          |  0

Total in 9 ms
$ 

--logLevel info” 标志提供了在构建模板时有用的额外信息。每一行以"INFO"或"WARN"开头的输出都存在,因为我们使用了这个标志。以“WARN”开头的行是警告信息。我们稍后再讨论。

We can verify that the command worked by looking at the directory again.

$ ls -l
total 8
drwxr-xr-x  3 liyan  wheel   96 Jun 12 13:28 archetypes
drwxr-xr-x  2 liyan  wheel   64 Jun 12 13:28 assets
drwxr-xr-x  2 liyan  wheel   64 Jun 12 13:28 content
drwxr-xr-x  2 liyan  wheel   64 Jun 12 13:28 data
-rw-r--r--  1 liyan  wheel   74 Jun 12 13:28 hugo.yaml
drwxr-xr-x  2 liyan  wheel   64 Jun 12 13:28 i18n
drwxr-xr-x  2 liyan  wheel   64 Jun 12 13:28 layouts
drwxr-xr-x  6 liyan  wheel  192 Jun 12 13:30 public
drwxr-xr-x  2 liyan  wheel   64 Jun 12 13:28 static
drwxr-xr-x  2 liyan  wheel   64 Jun 12 13:28 themes
$

See that new public/ directory? Hugo placed all generated content there. When you’re ready to publish your web site, that’s the place to start. For now, though, let’s just confirm that we have what we’d expect from a site with no content.

$ ls -l public
total 16
drwxr-xr-x  3 liyan  wheel   96 Jun 12 13:30 categories
-rw-r--r--  1 liyan  wheel  445 Jun 12 13:30 index.xml
-rw-r--r--  1 liyan  wheel  341 Jun 12 13:30 sitemap.xml
drwxr-xr-x  3 liyan  wheel   96 Jun 12 13:30 tags
$ 

Hugo created two XML files, which is standard, but there are no HTML files.

Test the New Site

Verify that you can run the built-in web server. It will dramatically shorten your development cycle if you do. Start it by running the “server” command. If it is successful, you will see output similar to the following:

$ hugo server --verbose
WARN  found no layout file for "html" for kind "home": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.
WARN  found no layout file for "html" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.

                   | EN
-------------------+-----
  Pages            |  4
  Paginator pages  |  0
  Non-page files   |  0
  Static files     |  0
  Processed images |  0
  Aliases          |  0
  Cleaned          |  0

Built in 2 ms
Environment: "development"
Serving pages from disk
Web Server is available at http://localhost:1313/ (bind address 127.0.0.1)
Press Ctrl+C to stop

Connect to the listed URL (it’s on the line that starts with “Web Server”). If everything is working correctly, you should get a page that shows the following:

index.xml
sitemap.xml

That’s a listing of your public/ directory. Hugo didn’t create a home page because our site has no content. When there’s no index.html file in a directory, the server lists the files in the directory, which is what you should see in your browser.

Let’s go back and look at those warnings again.

WARN  found no layout file for "html" for kind "home": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.
WARN  found no layout file for "html" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.

That second warning is easier to explain. We haven’t created a template to be used to generate “page not found errors.” The 404 message is a topic for a separate tutorial.

第一个警告是生成类型为首页的提示(kind “home”)。我们需要提供 layouts/home.html 模版来生成首页。

第二个警告是生成类型为分类的提示(kind “taxonomy”)。我们需要提供 layouts/terms.html 模版来生成分类。

现在已经有了一个能够运行的网站,我们可以在此基础上进行构建。剩下的就是添加一些内容和一个主题来显示它。

Create a New Theme

Hugo 没有附带默认主题。官网上提供了大量可用的第三方主题,Hugo 附带一个创建新主题的命令:hugo new theme <theme name>

我们要创建一个叫 “twotwo” 的新主题,由于本教程的目标是展示如何填充文件以注入内容,因此主题将不包含任何 CSS(新版本的 Hugo 在创建主题时,已经包含了 CSS 和 JS)。换句话说,丑陋但实用。

$ hugo env
hugo v0.132.1+extended darwin/amd64 BuildDate=2024-08-13T10:10:10Z VendorInfo=brew
GOOS="darwin"
GOARCH="amd64"
GOVERSION="go1.22.6"
github.com/sass/libsass="3.6.5"
github.com/webmproject/libwebp="v1.3.2"

所有主题对内容和布局都有自己的看法。强烈建议使模板更简单,使用个性化的参数会使主题更难使用。当你构建一个主题时,请考虑使用其他主题所使用的术语。

Create a Skeleton

Use the hugo “new” command to create the skeleton of a theme. This creates the directory structure and places empty files for you to fill out.

$ hugo new theme twotwo
Creating new theme in ./themes/twotwo

$ ls -l
drwxr-xr-x    - liyan 13 May 20:11 archetypes
drwxr-xr-x    - liyan 24 May 19:37 content
drwxr-xr-x    - liyan 23 May 16:35 layouts
drwxr-xr-x    - liyan  4 Jun 16:27 public
drwxr-xr-x    - liyan 14 May 17:50 static
drwxr-xr-x    - liyan 12 Jun 11:57 themes
.rw-r--r-- 3.2k liyan 23 May 21:24 hugo.yml
.rw-r--r-- 1.4k liyan 23 May 21:32 README.md

$ find themes/twotwo -type f | xargs ls -l
 1069 Aug 14 11:00 themes/twotwo/LICENSE
   61 Aug 14 11:00 themes/twotwo/README.md
  102 Aug 14 11:00 themes/twotwo/archetypes/default.md
  284 Aug 14 11:00 themes/twotwo/assets/css/main.css
   49 Aug 14 11:00 themes/twotwo/assets/js/main.js
  279 Aug 14 11:00 themes/twotwo/content/_index.md
  367 Aug 14 11:00 themes/twotwo/content/posts/_index.md
  812 Aug 14 11:00 themes/twotwo/content/posts/post-1.md
  940 Aug 14 11:00 themes/twotwo/content/posts/post-2.md
19224 Aug 14 11:00 themes/twotwo/content/posts/post-3/bryce-canyon.jpg
  996 Aug 14 11:00 themes/twotwo/content/posts/post-3/index.md
  335 Aug 14 11:00 themes/twotwo/hugo.toml
  354 Aug 14 11:00 themes/twotwo/layouts/_default/baseof.html
  174 Aug 14 11:00 themes/twotwo/layouts/_default/home.html
  187 Aug 14 11:00 themes/twotwo/layouts/_default/list.html
  325 Aug 14 11:00 themes/twotwo/layouts/_default/single.html
   54 Aug 14 11:00 themes/twotwo/layouts/partials/footer.html
  257 Aug 14 11:00 themes/twotwo/layouts/partials/head.html
  351 Aug 14 11:00 themes/twotwo/layouts/partials/head/css.html
  429 Aug 14 11:00 themes/twotwo/layouts/partials/head/js.html
   84 Aug 14 11:00 themes/twotwo/layouts/partials/header.html
 1343 Aug 14 11:00 themes/twotwo/layouts/partials/menu.html
  554 Aug 14 11:00 themes/twotwo/layouts/partials/terms.html
15406 Aug 14 11:00 themes/twotwo/static/favicon.ico
  830 Aug 14 11:00 themes/twotwo/theme.toml
$ 

这个框架包括模板(以 .html 结尾的文件)、许可文件(LICENSE)、主题的描述(theme.toml),以及一个空原型。

Please take a minute to fill out the theme.toml and LICENSE files. They’re optional, but if you’re going to be distributing your theme, it tells the world who to praise (or blame). It’s also nice to declare the license so that people will know how they can use the theme.

$ vi themes/twotwo/theme.toml
name = 'Theme name'
license = 'MIT'
licenselink = 'https://github.com/owner/repo/LICENSE'
description = 'Theme description'

# The home page of the theme, where the source can be found
homepage = 'https://github.com/twotwo/hugo-theme-twotwo'
:wq

## also edit themes/twotwo/LICENSE.md and change
## the bit that says "YOUR_NAME_HERE"

Note that the the skeleton’s template files are empty. Don’t worry, we’ll be changing that shortly.

$ find themes/twotwo -name '*.html' | xargs ls -l
themes/twotwo/layouts/_default/baseof.html
themes/twotwo/layouts/_default/home.html
themes/twotwo/layouts/_default/list.html
themes/twotwo/layouts/_default/single.html
themes/twotwo/layouts/partials/footer.html
themes/twotwo/layouts/partials/head.html
themes/twotwo/layouts/partials/head/css.html
themes/twotwo/layouts/partials/head/js.html
themes/twotwo/layouts/partials/header.html
themes/twotwo/layouts/partials/menu.html
themes/twotwo/layouts/partials/terms.html

Update the Configuration File to Use the Theme

既然我们已经有了一个可以使用的主题,那么最好将主题名称添加到配置文件中。这是可选的,因为总是可以在所有命令中添加“-t twotwo”。我喜欢把它放在配置文件中,因为我喜欢更短的命令行。如果你没有将它放入配置文件或在命令行中指定它,那么你就使用不了你期望使用的模板。

Edit the file to add the theme, add a title for the site, and specify that all of our content will use the YAML format.

$ vi hugo.yaml
baseURL: "http://li3huo.com/"
title: Demo Site
copyright: © 2005 ~ 2024
theme: towtwo
:wq

$

Generate the Site

Now that we have an empty theme, let’s generate the site again.

$ rm -rf public resources
$ hugo --logLevel info
Start building sites …
hugo v0.126.3+extended darwin/amd64 BuildDate=2024-06-02T13:02:43Z VendorInfo=brew

INFO  static: syncing static files to / duration 574.283µs
INFO  build:  step process substep collect files 6 files_total 6 pages_total 5 resources_total 1 duration 760.226µs
INFO  build:  step process duration 1.731464ms
INFO  build:  step assemble duration 695.993µs
INFO  build:  step render substep pages site en outputFormat html duration 12.782324ms
INFO  build:  step render substep pages site en outputFormat rss duration 1.207044ms
INFO  build:  step render pages 18 content 10 duration 14.075383ms
INFO  build:  step postProcess duration 13.424µs
INFO  build:  duration 16.664339ms

                   | EN
-------------------+-----
  Pages            | 18
  Paginator pages  |  0
  Non-page files   |  1
  Static files     |  1
  Processed images |  0
  Aliases          |  0
  Cleaned          |  0

Total in 25 ms
$

Did you notice that the output is different? The warning message for the home page has disappeared and we have an additional information line saying that Hugo is syncing from the theme’s directory.

Let’s check the public/ directory to see what Hugo’s created.

$ ls -l public
total 56
drwxr-xr-x  4 liyan  wheel    128 Jun 12 12:59 categories
drwxr-xr-x  3 liyan  wheel     96 Jun 12 12:59 css
-rw-r--r--  1 liyan  wheel  15406 Jun 12 12:54 favicon.ico
-rw-r--r--  1 liyan  wheel   2911 Jun 12 12:59 index.html
-rw-r--r--  1 liyan  wheel   2772 Jun 12 12:59 index.xml
drwxr-xr-x  3 liyan  wheel     96 Jun 12 12:59 js
drwxr-xr-x  7 liyan  wheel    224 Jun 12 12:59 posts
-rw-r--r--  1 liyan  wheel   1207 Jun 12 12:59 sitemap.xml
drwxr-xr-x  7 liyan  wheel    224 Jun 12 12:59 tags
$

Notice four things:

  1. Hugo created a home page. This is the file public/index.html.
  2. Hugo created a css/ directory.
  3. Hugo created a js/ directory.
  4. Hugo claimed that it created 0 pages. It created a file and copied over static files, but didn’t create any pages. That’s because it considers a “page” to be a file created directly from a content file. It doesn’t count things like the index.html files that it creates automatically.

The Home Page

Hugo supports many different types of templates. The home page is special because it gets its own type of template and its own template file. The file, layouts/index.html, is used to generate the HTML for the home page. The Hugo documentation says that this is the only required template, but that depends. Hugo’s warning message shows that it looks for three different templates:

WARN: 2014/09/29 Unable to locate layout: [index.html _default/list.html _default/single.html]

If it can’t find any of these, it completely skips creating the home page. We noticed that when we built the site without having a theme installed.

When Hugo created our theme, it created an empty home page template. Now, when we build the site, Hugo finds the template and uses it to generate the HTML for the home page. Since the template file is empty, the HTML file is empty, too. If the template had any rules in it, then Hugo would have used them to generate the home page.

$ find . -name index.html | xargs ls -l
-rw-r--r--  1 quoha  staff  0 Sep 29 20:21 ./public/index.html
-rw-r--r--  1 quoha  staff  0 Sep 29 17:31 ./themes/zafta/layouts/index.html
$ 

The Magic of Static

Hugo does two things when generating the site. It uses templates to transform content into HTML and it copies static files into the site. Unlike content, static files are not transformed. They are copied exactly as they are.

Hugo assumes that your site will use both CSS and JavaScript, so it creates directories in your theme to hold them. Remember opinions? Well, Hugo’s opinion is that you’ll store your CSS in a directory named css/ and your JavaScript in a directory named js/. If you don’t like that, you can change the directory names in your theme directory or even delete them completely. Hugo’s nice enough to offer its opinion, then behave nicely if you disagree.

$ find themes/zafta -type d | xargs ls -ld
drwxr-xr-x  7 quoha  staff  238 Sep 29 17:38 themes/zafta
drwxr-xr-x  3 quoha  staff  102 Sep 29 17:31 themes/zafta/archetypes
drwxr-xr-x  5 quoha  staff  170 Sep 29 17:31 themes/zafta/layouts
drwxr-xr-x  4 quoha  staff  136 Sep 29 17:31 themes/zafta/layouts/_default
drwxr-xr-x  4 quoha  staff  136 Sep 29 17:31 themes/zafta/layouts/partials
drwxr-xr-x  4 quoha  staff  136 Sep 29 17:31 themes/zafta/static
drwxr-xr-x  2 quoha  staff   68 Sep 29 17:31 themes/zafta/static/css
drwxr-xr-x  2 quoha  staff   68 Sep 29 17:31 themes/zafta/static/js
$ 

The Theme Development Cycle

When you’re working on a theme, you will make changes in the theme’s directory, rebuild the site, and check your changes in the browser. Hugo makes this very easy:

  1. Purge the public/ directory.
  2. Run the built in web server in watch mode.
  3. Open your site in a browser.
  4. Update the theme.
  5. Glance at your browser window to see changes.
  6. Return to step 4.

I’ll throw in one more opinion: never work on a theme on a live site. Always work on a copy of your site. Make changes to your theme, test them, then copy them up to your site. For added safety, use a tool like Git to keep a revision history of your content and your theme. Believe me when I say that it is too easy to lose both your mind and your changes.

Check the main Hugo site for information on using Git with Hugo.

Purge the public/ Directory

When generating the site, Hugo will create new files and update existing ones in the public/ directory. It will not delete files that are no longer used. For example, files that were created in the wrong directory or with the wrong title will remain. If you leave them, you might get confused by them later. I recommend cleaning out your site prior to generating it.

Note: If you’re building on an SSD, you should ignore this. Churning on a SSD can be costly.

Hugo’s Watch Option

Hugo’s “--watch” option will monitor the content/ and your theme directories for changes and rebuild the site automatically.

Live Reload

Hugo’s built in web server supports live reload. As pages are saved on the server, the browser is told to refresh the page. Usually, this happens faster than you can say, “Wow, that’s totally amazing.”

Development Commands

Use the following commands as the basis for your workflow.

## purge old files. hugo will recreate the public directory.
##
$ rm -rf public
##
## run hugo in watch mode
##
$ hugo server --watch --verbose

Here’s sample output showing Hugo detecting a change to the template for the home page. Once generated, the web browser automatically reloaded the page. I’ve said this before, it’s amazing.

$ rm -rf public
$ hugo server --watch --verbose
INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml
INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/
INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/
WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html]
0 draft content 
0 future content 
0 pages created 
0 tags created
0 categories created
in 2 ms
Watching for changes in /Users/quoha/Sites/zafta/content
Serving pages from /Users/quoha/Sites/zafta/public
Web Server is available at http://localhost:1313
Press Ctrl+C to stop
INFO: 2014/09/29 File System Event: ["/Users/quoha/Sites/zafta/themes/zafta/layouts/index.html": MODIFY|ATTRIB]
Change detected, rebuilding site

WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html]
0 draft content 
0 future content 
0 pages created 
0 tags created
0 categories created
in 1 ms

Base Template

https://www.youtube.com/watch?v=QVOMCYitLEc

Base templates 主要介绍了 Hugo 静态网站生成器中的基础模板(base templates)和块(block)构造的使用方法,以及如何通过它们定义和覆盖网站的主要模板结构。

在 _default/baseof.html 文件中定义了一个简单的基础模板,它为所有页面提供了一个通用的 HTML 结构,包括头部、标题和页脚块。这些块可以包含默认内容,并且可以在特定的模板中被覆盖。

Home Page Template

https://www.youtube.com/watch?v=ut1xtRZ1QOA

Home templates 介绍了 Hugo 网站首页模板的使用和配置方法。

Hugo 允许用户为网站的首页创建一个独特的模板。首页模板是构建网站时唯一必需的模板,对于引导新网站和模板或开发单页网站非常有用。

Hugo 在查找首页模板时按照以下顺序进行查找:

  1. layouts/index.html
  2. layouts/home.html
  3. layouts/list.html
  4. layouts/_default/{index, home, list}.html 首页内容和 front matter 可以通过在 content 文件夹根目录下的 _index.md 文件添加。

vi themes/twotwo/layouts/_default/home.html

{{ define "main" }}
  {{ .Content }}
  {{ range first 7 site.RegularPages }}
    <h2><a href="{{ .RelPermalink }}">{{ .LinkTitle }}</a></h2>
    {{ .Summary }}
  {{ end }}
{{ end }}

首页显示最新 7 篇(first 7) Post。

Make a Static Home Page

Build the web site and then verify the results.

$ hugo --logLevel info
Start building sites …
hugo v0.132.1+extended darwin/amd64 BuildDate=2024-08-13T10:10:10Z VendorInfo=brew
...

                   | EN
-------------------+------
  Pages            | 343
  Paginator pages  |   0
  Non-page files   |   5
  Static files     | 106
  Processed images |   0
  Aliases          |  11
  Cleaned          |   0

Total in 701 ms


$ find public -type f -name '*.html' | xargs ls -l
$ ll public/index.html
.rw-r--r-- 2.5k liyan 15 Aug 10:10 public/index.html

Live Reload

Note: If you’re running the server with the --watch option, you’ll see different content in the file:

$ cat public/index.html 
<!DOCTYPE html> 
<html> 
<body> 
  <p>hugo says hello!</p> 
<script>document.write('<script src="http://' 
        + (location.host || 'localhost').split(':')[0] 
    + ':1313/livereload.js?mindelay=10"></' 
        + 'script>')</script></body> 
</html>

When you use --watch, the Live Reload script is added by Hugo. Look for live reload in the documentation to see what it does and how to disable it.

Build a “Dynamic” Home Page

“Dynamic home page?” Hugo’s a static web site generator, so this seems an odd thing to say. I mean let’s have the home page automatically reflect the content in the site every time Hugo builds it. We’ll use iteration in the template to do that.

Create New Posts

Now that we have the home page generating static content, let’s add some content to the site. We’ll display these posts as a list on the home page and on their own page, too.

Hugo has a command to generate a skeleton post, just like it does for sites and themes.

$ hugo --verbose new post/first.md
INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml
INFO: 2014/09/29 attempting to create  post/first.md of post
INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/default.md
ERROR: 2014/09/29 Unable to Cast <nil> to map[string]interface{}

$ 

That wasn’t very nice, was it?

The “new” command uses an archetype to create the post file. Hugo created an empty default archetype file, but that causes an error when there’s a theme. For me, the workaround was to create an archetypes file specifically for the post type.

$ vi themes/zafta/archetypes/post.md
---
Description = ""
Tags = []
Categories = []
---
:wq

$ find themes/zafta/archetypes -type f | xargs ls -l
-rw-r--r--  1 quoha  staff   0 Sep 29 21:53 themes/zafta/archetypes/default.md
-rw-r--r--  1 quoha  staff  51 Sep 29 21:54 themes/zafta/archetypes/post.md

$ hugo --verbose new post/first.md
INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml
INFO: 2014/09/29 attempting to create  post/first.md of post
INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/post.md
INFO: 2014/09/29 creating /Users/quoha/Sites/zafta/content/post/first.md
/Users/quoha/Sites/zafta/content/post/first.md created

$ hugo --verbose new post/second.md
INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml
INFO: 2014/09/29 attempting to create  post/second.md of post
INFO: 2014/09/29 curpath: /Users/quoha/Sites/zafta/themes/zafta/archetypes/post.md
INFO: 2014/09/29 creating /Users/quoha/Sites/zafta/content/post/second.md
/Users/quoha/Sites/zafta/content/post/second.md created

$ ls -l content/post
total 16
-rw-r--r--  1 quoha  staff  104 Sep 29 21:54 first.md
-rw-r--r--  1 quoha  staff  105 Sep 29 21:57 second.md

$ cat content/post/first.md 
---
Categories = []
Description = ""
Tags = []
date: "2014-09-29T21:54:53-05:00"
title: "first"

---
my first post

$ cat content/post/second.md 
---
Categories = []
Description = ""
Tags = []
date: "2014-09-29T21:57:09-05:00"
title: "second"

---
my second post

$ 

Build the web site and then verify the results.

$ rm -rf public
$ hugo --verbose
INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml
INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/
INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/
INFO: 2014/09/29 found taxonomies: map[string]string{"category":"categories", "tag":"tags"}
WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html]
0 draft content 
0 future content 
2 pages created 
0 tags created
0 categories created
in 4 ms
$

The output says that it created 2 pages. Those are our new posts:

$ find public -type f -name '*.html' | xargs ls -l
-rw-r--r--  1 quoha  staff  78 Sep 29 22:13 public/index.html
-rw-r--r--  1 quoha  staff   0 Sep 29 22:13 public/post/first/index.html
-rw-r--r--  1 quoha  staff   0 Sep 29 22:13 public/post/index.html
-rw-r--r--  1 quoha  staff   0 Sep 29 22:13 public/post/second/index.html
$

The new files are empty because because the templates used to generate the content are empty. The homepage doesn’t show the new content, either. We have to update the templates to add the posts.

List and Single Templates

In Hugo, we have three major kinds of templates. There’s the home page template that we updated previously. It is used only by the home page. We also have “single” templates which are used to generate output for a single content file. We also have “list” templates that are used to group multiple pieces of content before generating output.

Generally speaking, list templates are named “list.html” and single templates are named “single.html.”

There are three other types of templates: partials, content views, and terms. We will not go into much detail on these.

Add Content to the Homepage

The home page will contain a list of posts. Let’s update its template to add the posts that we just created. The logic in the template will run every time we build the site.

$ vi themes/zafta/layouts/index.html 
<!DOCTYPE html>
<html>
<body>
  {{ range first 10 .Data.Pages }}
    <h1>{{ .Title }}</h1>
  {{ end }}
</body>
</html>
:wq

$

Hugo uses the Go template engine. That engine scans the template files for commands which are enclosed between “{{” and “}}”. In our template, the commands are:

  1. range
  2. .Title
  3. end

The “range” command is an iterator. We’re going to use it to go through the first ten pages. Every HTML file that Hugo creates is treated as a page, so looping through the list of pages will look at every file that will be created.

The “.Title” command prints the value of the “title” variable. Hugo pulls it from the front matter in the Markdown file.

The “end” command signals the end of the range iterator. The engine loops back to the top of the iteration when it finds “end.” Everything between the “range” and “end” is evaluated every time the engine goes through the iteration. In this file, that would cause the title from the first ten pages to be output as heading level one.

It’s helpful to remember that some variables, like .Data, are created before any output files. Hugo loads every content file into the variable and then gives the template a chance to process before creating the HTML files.

Build the web site and then verify the results.

$ rm -rf public
$ hugo --verbose
INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml
INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/
INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/
INFO: 2014/09/29 found taxonomies: map[string]string{"tag":"tags", "category":"categories"}
WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html]
0 draft content 
0 future content 
2 pages created 
0 tags created
0 categories created
in 4 ms
$ find public -type f -name '*.html' | xargs ls -l 
-rw-r--r--  1 quoha  staff  94 Sep 29 22:23 public/index.html
-rw-r--r--  1 quoha  staff   0 Sep 29 22:23 public/post/first/index.html
-rw-r--r--  1 quoha  staff   0 Sep 29 22:23 public/post/index.html
-rw-r--r--  1 quoha  staff   0 Sep 29 22:23 public/post/second/index.html
$ cat public/index.html 
<!DOCTYPE html>
<html>
<body>
  
    <h1>second</h1>
  
    <h1>first</h1>
  
</body>
</html>
$

恭喜,主页显示了这两篇文章的标题。帖子本身仍然是空的,但让我们花一点时间来欣赏我们所做的事情。模板现在动态地生成了输出。信不信由你,通过在那些花括号内插入 range 命令,你已经学习了构建主题所需的所有知识。真正剩下的就是了解将使用哪个模板来生成每个内容文件,并熟悉模板引擎的命令。

如果这是完全正确的,本教程将会更短。有一些事情你需要知道,这将使创建一个新的模板更容易。不过,别担心,这就是接下来的内容。

Add Content to the Posts

We’re working with posts, which are in the content/post/ directory. That means that their section is “post” (and if we don’t do something weird, their type is also “post”).

Hugo 使用 section 和 type 为每一段内容找到模板文件。Hugo 将首先查找与 section 或 type 名匹配的模板文件,如果没找到,那么它将在 _default/ 目录中查找。在讨论 categories 和 tags 时,我们将讨论一些变化,但现在我们可以假设 Hugo 将尝试post/single.html,然后是 _default/single.html

Now that we know the search rule, let’s see what we actually have available:

$ find themes/zafta -name single.html | xargs ls -l
-rw-r--r--  1 quoha  staff  132 Sep 29 17:31 themes/zafta/layouts/_default/single.html

We could create a new template, post/single.html, or change the default. Since we don’t know of any other content types, let’s start with updating the default.

记住,我们还没有创建模板的任何内容最终都会使用这个模板。这可能是好事,也可能是坏事。不好是因为我知道我们将添加不同类型的内容,我们将最终取消我们所做的一些更改。这很好,因为我们将能够看到立即的结果。从这里开始也很好,因为我们可以开始为站点构建基本布局。随着我们添加更多的内容类型,我们将重构这个文件并移动逻辑。Hugo 让这个过程变得很轻松,所以我们接受这个代价,继续前进。

Please see the Hugo documentation on template rendering for all the details on determining which template to use. And, as the docs mention, if you’re building a single page application (SPA) web site, you can delete all of the other templates and work with just the default single page. That’s a refreshing amount of joy right there.

Update the Template File

$ vi themes/zafta/layouts/_default/single.html 
<!DOCTYPE html>
<html>
<head>
  <title>{{ .Title }}</title>
</head>
<body>
  <h1>{{ .Title }}</h1>
  {{ .Content }}
</body>
</html>
:wq

$

Build the web site and verify the results.

$ rm -rf public
$ hugo --verbose
INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml
INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/
INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/
INFO: 2014/09/29 found taxonomies: map[string]string{"tag":"tags", "category":"categories"}
WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html]
0 draft content 
0 future content 
2 pages created 
0 tags created
0 categories created
in 4 ms

$ find public -type f -name '*.html' | xargs ls -l
-rw-r--r--  1 quoha  staff   94 Sep 29 22:40 public/index.html
-rw-r--r--  1 quoha  staff  125 Sep 29 22:40 public/post/first/index.html
-rw-r--r--  1 quoha  staff    0 Sep 29 22:40 public/post/index.html
-rw-r--r--  1 quoha  staff  128 Sep 29 22:40 public/post/second/index.html

$ cat public/post/first/index.html 
<!DOCTYPE html>
<html>
<head>
  <title>first</title>
</head>
<body>
  <h1>first</h1>
  <p>my first post</p>

</body>
</html>

$ cat public/post/second/index.html 
<!DOCTYPE html>
<html>
<head>
  <title>second</title>
</head>
<body>
  <h1>second</h1>
  <p>my second post</p>

</body>
</html>
$

Notice that the posts now have content. You can go to localhost:1313/post/first to verify.

Linking to Content

The posts are on the home page. Let’s add a link from there to the post. Since this is the home page, we’ll update its template.

$ vi themes/zafta/layouts/index.html
<!DOCTYPE html>
<html>
<body>
  {{ range first 10 .Data.Pages }}
    <h1><a href="{{ .Permalink }}">{{ .Title }}</a></h1>
  {{ end }}
</body>
</html>

Build the web site and verify the results.

$ rm -rf public
$ hugo --verbose
INFO: 2014/09/29 Using config file: /Users/quoha/Sites/zafta/config.toml
INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/themes/zafta/static/ to /Users/quoha/Sites/zafta/public/
INFO: 2014/09/29 syncing from /Users/quoha/Sites/zafta/static/ to /Users/quoha/Sites/zafta/public/
INFO: 2014/09/29 found taxonomies: map[string]string{"tag":"tags", "category":"categories"}
WARN: 2014/09/29 Unable to locate layout: [404.html theme/404.html]
0 draft content 
0 future content 
2 pages created 
0 tags created
0 categories created
in 4 ms

$ find public -type f -name '*.html' | xargs ls -l
-rw-r--r--  1 quoha  staff  149 Sep 29 22:44 public/index.html
-rw-r--r--  1 quoha  staff  125 Sep 29 22:44 public/post/first/index.html
-rw-r--r--  1 quoha  staff    0 Sep 29 22:44 public/post/index.html
-rw-r--r--  1 quoha  staff  128 Sep 29 22:44 public/post/second/index.html

$ cat public/index.html 
<!DOCTYPE html>
<html>
<body>
  
    <h1><a href="/post/second/">second</a></h1>
  
    <h1><a href="/post/first/">first</a></h1>
  
</body>
</html>

$

Create a Post Listing

We have the posts displaying on the home page and on their own page. We also have a file public/post/index.html that is empty. Let’s make it show a list of all posts (not just the first ten).

We need to decide which template to update. This will be a listing, so it should be a list template. Let’s take a quick look and see which list templates are available.

$ find themes/zafta -name list.html | xargs ls -l
-rw-r--r--  1 quoha  staff  0 Sep 29 17:31 themes/zafta/layouts/_default/list.html

As with the single post, we have to decide to update _default/list.html or create post/list.html. We still don’t have multiple content types, so let’s stay consistent and update the default list template.

Creating Top Level Pages

Let’s add an “about” page and display it at the top level (as opposed to a sub-level like we did with posts).

The default in Hugo is to use the directory structure of the content/ directory to guide the location of the generated html in the public/ directory. Let’s verify that by creating an “about” page at the top level:

$ vi content/about.md 
---
date: "2010-06-13"
layout: posts
title: 关于
---

About twotwo & apple

Slogan: Life is a journey, not a destination. Let's enjoy the process, learn from our experiences, and become better versions of ourselves! 🌟


### Code base

- WordPress Posts to Markdown File:<https://github.com/twotwo/wp2octopress>
- Hugo:<https://gohugo.io/>
- Hugo Theme: <https://github.com/adityatelange/hugo-PaperMod>
- 本站代码: <https://github.com/twotwo/hugo-template>

<!--more-->

:wq

Generate the web site and verify the results.

$ find public -name '*.html' | xargs ls -l
-rw-r--r--  1 liyan  staff   12454 Jun 12 10:39 public/about/index.html
...

Notice that the page wasn’t created at the top level. It was created in a sub-directory named ‘about/’.

One other thing. Take a look at the home page.

$ cat public/index.html
<!DOCTYPE html>
<html>
<body>
    <h1><a href="http://localhost:1313/post/theme/">creating a new theme</a></h1>
    <h1><a href="http://localhost:1313/about-time/">about</a></h1>
    <h1><a href="http://localhost:1313/post/second-post/">second</a></h1>
    <h1><a href="http://localhost:1313/post/first-post/">first</a></h1>
<script>document.write('<script src="http://'
        + (location.host || 'localhost').split(':')[0]
		+ ':1313/livereload.js?mindelay=10"></'
        + 'script>')</script></body>
</html>

Notice that the “about” link is listed with the posts? That’s not desirable, so let’s change that first.

$ vi themes/zafta/layouts/index.html
<!DOCTYPE html>
<html>
<body>
  <h1>posts</h1>
  {{ range first 10 .Data.Pages }}
    {{ if eq .Type "post"}}
      <h2><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
    {{ end }}
  {{ end }}

  <h1>pages</h1>
  {{ range .Data.Pages }}
    {{ if eq .Type "page" }}
      <h2><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
    {{ end }}
  {{ end }}
</body>
</html>
:wq

Generate the web site and verify the results. The home page has two sections, posts and pages, and each section has the right set of headings and links in it.

But, that about page still renders to about-time/index.html.

$ find public -name '*.html' | xargs ls -l
-rw-rw-r--  1 mdhender  staff    334 Sep 27 15:33 public/about-time/index.html
-rw-rw-r--  1 mdhender  staff    645 Sep 27 15:33 public/index.html
-rw-rw-r--  1 mdhender  staff    358 Sep 27 15:33 public/post/first-post/index.html
-rw-rw-r--  1 mdhender  staff      0 Sep 27 15:33 public/post/index.html
-rw-rw-r--  1 mdhender  staff    342 Sep 27 15:33 public/post/second-post/index.html

Knowing that hugo is using the slug to generate the file name, the simplest solution is to change the slug. Let’s do it the hard way and change the permalink in the configuration file.

$ vi config.toml
[permalinks]
	page = "/:title/"
	about = "/:filename/"

Generate the web site and verify that this didn’t work. Hugo lets “slug” or “URL” override the permalinks setting in the configuration file. Go ahead and comment out the slug in content/about.md, then generate the web site to get it to be created in the right place.

Sharing Templates

If you’ve been following along, you probably noticed that posts have titles in the browser and the home page doesn’t. That’s because we didn’t put the title in the home page’s template (layouts/index.html). That’s an easy thing to do, but let’s look at a different option.

We can put the common bits into a shared template that’s stored in the themes/zafta/layouts/partials/ directory.

In Hugo, a partial is a sugar-coated template. Normally a template reference has a path specified. Partials are different. Hugo searches for them along a TODO defined search path. This makes it easier for end-users to override the theme’s presentation.

$ vi themes/zafta/layouts/partials/header.html
<!DOCTYPE html>
<html>
<head>
	<title>{{ .Title }}</title>
</head>
<body>
:wq

$ vi themes/zafta/layouts/partials/footer.html
</body>
</html>
:wq

Update the Home Page Template to Use the Partials

The most noticeable difference between a template call and a partials call is the lack of path:

{{ template "theme/partials/header.html" . }}

versus

{{ partial "header.html" . }}

Both pass in the context.

Let’s change the home page template to use these new partials.

$ vi themes/zafta/layouts/index.html
{{ partial "header.html" . }}

  <h1>posts</h1>
  {{ range first 10 .Data.Pages }}
    {{ if eq .Type "post"}}
      <h2><a href="{{ .Permalink }}">{{ .Title }}</a></h2>
    {{ end }}
  {{ end }}

  <h1>pages</h1>
  {{ range .Data.Pages }}
    {{ if or (eq .Type "page") (eq .Type "about") }}
      <h2><a href="{{ .Permalink }}">{{ .Type }} - {{ .Title }} - {{ .RelPermalink }}</a></h2>
    {{ end }}
  {{ end }}

{{ partial "footer.html" . }}
:wq

Generate the web site and verify the results. The title on the home page is now “your title here”, which comes from the “title” variable in the config.toml file.

Update the Default Single Template to Use the Partials

$ vi themes/zafta/layouts/_default/single.html
{{ partial "header.html" . }}

  <h1>{{ .Title }}</h1>
  {{ .Content }}

{{ partial "footer.html" . }}
:wq

Generate the web site and verify the results. The title on the posts and the about page should both reflect the value in the markdown file.

Add “Date Published” to Posts

It’s common to have posts display the date that they were written or published, so let’s add that. The front matter of our posts has a variable named “date.” It’s usually the date the content was created, but let’s pretend that’s the value we want to display.

Add “Date Published” to the Template

We’ll start by updating the template used to render the posts. The template code will look like:

{{ .Date.Format "Mon, Jan 2, 2006" }}

Posts use the default single template, so we’ll change that file.

$ vi themes/zafta/layouts/_default/single.html
{{ partial "header.html" . }}

  <h1>{{ .Title }}</h1>
  <h2>{{ .Date.Format "Mon, Jan 2, 2006" }}</h2>
  {{ .Content }}

{{ partial "footer.html" . }}
:wq

Generate the web site and verify the results. The posts now have the date displayed in them. There’s a problem, though. The “about” page also has the date displayed.

As usual, there are a couple of ways to make the date display only on posts. We could do an “if” statement like we did on the home page. Another way would be to create a separate template for posts.

The “if” solution works for sites that have just a couple of content types. It aligns with the principle of “code for today,” too.

Let’s assume, though, that we’ve made our site so complex that we feel we have to create a new template type. In Hugo-speak, we’re going to create a section template.

Let’s restore the default single template before we forget.

$ mkdir themes/zafta/layouts/post
$ vi themes/zafta/layouts/post/single.html
{{ partial "header.html" . }}

  <h1>{{ .Title }}</h1>
  {{ .Content }}

{{ partial "footer.html" . }}
:wq

Now we’ll update the post’s version of the single template. If you remember Hugo’s rules, the template engine will use this version over the default.

$ vi themes/zafta/layouts/post/single.html
{{ partial "header.html" . }}

  <h1>{{ .Title }}</h1>
  <h2>{{ .Date.Format "Mon, Jan 2, 2006" }}</h2>
  {{ .Content }}

{{ partial "footer.html" . }}
:wq

Note that we removed the date logic from the default template and put it in the post template. Generate the web site and verify the results. Posts have dates and the about page doesn’t.

Don’t Repeat Yourself

DRY 是一个很好的设计目标,Hugo在这方面做得很好。好的模板的艺术之一是知道何时添加新模板,何时更新现有模板。当你在思考这个问题的时候,接受你要做一些重构工作的事实。Hugo让这变得简单而快速,所以有时延迟拆分模板是个好主意💡。

Last updated on 2024-08-15 16:56
Built with Hugo