點燈坊

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

Using Template Variable

Sam Xiao's Avatar 2022-01-11

We can use := to declare a template variable and = to re-assign it.

Version

Hugo 0.91

Page

variable000

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

Template Variable

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 := .Title }}
    {{ if not $title }}
    {{ $title = .Site.Title }}
    {{ end }}
    <title>{{ $title }}</title>
  </head>
  <body>
    <h1 class="text-4xl font-bold">{{ $title }}</h1>
  </body>
</html>

Line 8

{{ $title := .Title }}
  • $title : define $title by title page variable
  1. Template variable starts with a $ sign
  2. Template variable is declared by :=

Line 10

{{ $title = .Site.Title }}
  • $title : $title is re-assigned by title site variable
  1. Template variable is re-assigned by =

Line 12

<title>{{ $title }}</title>
  • $title : bind template variable

Conclusion

  • Template variable has to be started with a $ sign like PHP