We can use default to provide the default value of the template variable instead of using if else.
Version
Hugo 0.91
Page

Display title by page variable or site variable.
Page Variable
content/_index.md
---
title: My Blog
---
title: page variable defined in Markdown
Site Variable
config.json
{
"baseURL": "http://example.org/",
"languageCode": "en-us",
"title": "My New Hugo Site",
}
title: site variable defined inconfig.json
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
titlepage variable exists, it is a truthy value, show thetitlepage variable - If the
titlepage variable doesn’t exist, it is a falsy value, show thetitlesite variable
If we can provide a default value for
$title, we don’t have to useif elsestatement
default
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 := default .Site.Title .Title }}
<title>{{ $title }}</title>
</head>
<body>
<h1 class="text-4xl font-bold">{{ $title }}</h1>
</body>
</html>
Line 8
{{ $title := default .Site.Title .Title }}
default: a function to provide the default value.Site.Title: the first argument is the default value.Title: use the second argument if it exists
Hugo functions take their parameters separated by spaces
Line 9
<title>{{ $title }}</title>
$title : use the $title template variable directly without if else statement
Conclusion
defaultmakes the codebase clean and concise