點燈坊

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

Using if else for Truthy Value

Sam Xiao's Avatar 2022-01-11

We can use if else for truthy/falsy value in Go template language.

Version

Hugo 0.91

Page

if000

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

Conclusion

  • We have to use end with if else in Go template language