點燈坊

新しいことを始めるのに、遅すぎる挑戰はない

Hugo Template 簡介

Sam Xiao's Avatar 2024-04-30

Hugo 自帶 Template 語言,可將在 Markdown 的資料綁定到 HTML。

Version

Hugo 0.125.2

Page

overview000

  • MyBlogHello World 並非直接寫在 HTML,而是由 Markdown 所提供

Content

content/_index.md

---
title: My Blog
description: Hello World
subtitle: Blog for Myself
---
  • _index.md : homepage 的 front matter 與 content 位於 content 目錄下的 _index.md
  • title:Hugo 預設的 page variable
  • description:Hugo 預設的 page variable
  • subtitle : 使用者自定義的 page variable

Hugo 規定 homepage 所搭配的 Markdown 檔名必須是 _index.md,不可以是 index.md

Layout

layouts/index.html

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    {{ $title := "Hugo Lab" }}
    <title>{{ $title }}</title>
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
    <h1 class="title">{{ .Title }}</h1>
    <h2 class="description">{{ .Description }}</h2>
    <p class="subtitle">{{ .Params.Subtitle }}</p>
  </body>
</html>
  • index.html : 在 layout 根目錄下的 index.html 為 homepage 的 template
  • .Titletitle 為預設 page variable,因此可在 Page Object 下直接存取
  • .Descriptiondescription 為預設 page variable,因此可在 Page Object 下直接存取
  • .Params.Subtitlesubtitle 為使用者自定義的 page variable,並不存在於 Page Object,必須使用 Params Object 存取
  • Template 預設的 context 為 Page Object,因此可直接使用 . 存取 Page Object
  • Page variable 必須使用 Camelcase 存取

Style

static/style.css

.title {
  color: #f00;
  font-size: 2rem;
  font-weight: 700;
}

.description {
  font-size: 1.1rem;
}

.subtitle {
  font-size: 1rem;
  color: #00f;
}

Conclusion

  • 在 template 讀取 Markdown 的 front matter 時,必須考慮其為 內建自訂 的 page variable