點燈坊

失くすものさえない今が強くなるチャンスよ

Using default to Provide the Default Value

Sam Xiao's Avatar 2022-01-11

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

Version

Hugo 0.91

Page

default000

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 in config.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 title page variable exists, it is a truthy value, show the title page variable
  • If the title page variable doesn’t exist, it is a falsy value, show the title site variable

If we can provide a default value for $title, we don’t have to use if else statement

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

  • default makes the codebase clean and concise