次世代 Hugo

無駄を削ぎ、本質を研ぐ

在 Template 使用變數

Sam Xiao's Avatar 2025-06-28

我們可使用 := 在 Go template 內定義變數,並使用 = 改變變數。

Version

Hugo 0.91

Page

variable000

  • 顯示 Page variable 與 Site variable

Page Variable

content/_index.md

---
title: My Blog
---
  • title : 在 markdown 的 front matter 定義 Page variable

Site Variable

config.json

{
   "baseURL": "http://example.org/",
   "languageCode": "en-us",
   "title": "My New Hugo Site",
}
  • title:在 config.json 定義 Site variable

Template Variable

layouts/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="alpine.js" defer></script>
    <link rel="stylesheet" href="output.css" />
    {{ $title := .Title }}
    {{ if not $title }}
      {{ $title = .Site.Title }}
    {{ end }}
    <title>{{ $title }}</title>
  </head>
  <body>
    <h1 class="text-4xl font-bold">{{ $title }}</h1>
  </body>
</html>

Line 8

{{ $title := .Title }}
  • $title:以 title Page variable 定義 $title Template variable

第一次定義變數需使用 :=

Line 10

{{ $title = .Site.Title }}
  • $title : 以 title Site variable 定義 $title Template variable

第二次敢變變數需使用 =

Line 12

<title>{{ $title }}</title>
  • $title : 將 Template variable 綁定到 HTML

Conclusion

  • Template variable 必須如 PHP 一樣在變數前加上 $