次世代 Hugo

無駄を削ぎ、本質を研ぐ

if-使用 if else 處理 Truthy Value

Sam Xiao's Avatar 2025-06-27

我們可在 Go template 內使用 if else 處理 Truthy Value 或 Falsy Value。

Version

Hugo 0.91

Page

if000

  • 顯示 title page variable 或 title site variable

Content

content/_index.md

---
title: My Blog
---
  • title : title預設 的 page variable

if else

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" />
  </head>
  <body>
    {{ if .Title }}
      <h1 class="text-4xl font-bold">{{ .Title }}</h1>
    {{ else }}
      <h1 class="text-4xl font-bold">{{ .Site.Title }}</h1>
    {{ end }}
  </body>
</html>

Line 10

{{ if .Title }}
  <h1 class="text-4xl font-bold">{{ .Title }}</h1>
{{ else }}
  <h1 class="text-4xl font-bold">{{ .Site.Title }}</h1>
{{ end }}
  • if:如果 title page variable 存在,此為 truthy value,將顯示 title page variable
  • else:如果 title page variable 不存在,此為 falsy value,將顯示 title site variable

Conclusion

  • 與其他語言不同的是,Go template 的 if else 必須加上 end