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
My Blog
is a site variableMy 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 inconfig.json
Line 11
<h1>{{ .Title }}</h1>
.Title
:title
is a page variable defined in Markdown
Context
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 accesstitle
page variable by.Title
Hugo makes all the site variables in the
Page
context under theSite
key. That’s why we can accesstitle
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 thePage
context. So we have to use.Site
to access site variables