點燈坊

うまく使いさえすれば、時間はいつも十分にある

Relationship between dot, Site and Page Context

Sam Xiao's Avatar 2022-01-27

There are scope and context concepts in the Go template language. This post explains why we have to use . to access site variables and page variables.

Version

Hugo 0.92

Layout

context001

  • My Blog is a site variable
  • My Home is a page 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>{{ .Site.Title }}</title>
  </head>
  <body>
    <h1>{{ .Title }}</h1>
  </body>
</html>

Line 8

<title>{{ .Site.Title }}</title>
  • .Site.Title : title is a site variable defined in config.json

Line 11

<h1>{{ .Title }}</h1>
  • .Title : title is a page variable defined in Markdown

Context

context000

  • The current context in a template is represented by the .

  • In a Hugo layout, the context is set to the Page context. That’s why we can access title page variable by .Title

  • Hugo makes all the site variables in the Page context under the Site key. That’s why we can access title site variable by .Site.Title

Conclusion

  • Hugo sets the Page context to the current context. So we have to use . to access page variables
  • Hugo set all site variables under the Site key of the Page context. So we have to use .Site to access site variables