點燈坊

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

Using .Param to access User-defined Variable

Sam Xiao's Avatar 2022-01-11

For user-defined variable, we can either define it as site variable or page variable. $.Param reads page variable first. If it doesn’t exist, then read site variable.

Version

Hugo 0.91

Page

param000

The page shows Subtitle, which is a page variable.

Page Variable

content/_index.md

---
title: My Blog
description: Hello World
subtitle: Page Subtitle
---
  • title : default page variable defined by Hugo
  • description : default page variable defined by Hugo
  • subtitle : user-defined page variable

Site Variable

config.json

{
   "baseURL": "http://example.org/",
   "languageCode": "en-us",
   "title": "My New Hugo Site",
   "params": {
      "subtitle": "Site Subtitle",
   },
}
  • title : default site variable defined by Hugo
  • subtitle : user-defined site variable

$.Param

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 }}</title>
  </head>
  <body>
    <p class="text-red-500">{{ .Param "Subtitle" }}</p>
  </body>
</html>

Line 11

<p class="text-red-500">{{ .Param "Subtitle" }}</p>

.Param : provide the subtitle page variable and falls back to the subtitle site variable if the page variable is not present

Conclusion

  • .Param makes the codebase clean and concise