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

- 顯示
titlepage variable 或titlesite 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:如果titlepage variable 存在,此為 truthy value,將顯示titlepage variableelse:如果titlepage variable 不存在,此為 falsy value,將顯示titlesite variable
Conclusion
- 與其他語言不同的是,Go template 的
if else必須加上end