We can use if else
for truthy/falsy value in Go template language.
Version
Hugo 0.91
Page
Display title
page variable or title
site variable.
Content
content/_index.md
---
title: My Blog
---
title
: default 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 the
title
page variable exists, it is a truthy value, show thetitle
page variable - If the
title
page variable doesn’t exist, it is a falsy value, show thetitle
site variable
Conclusion
- We have to use
end
withif else
in Go template language