點燈坊

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

Using Site Variables to Store Custom Data

Sam Xiao's Avatar 2022-01-19

For site-level custom data, we can store them on the params section of config.json.

Version

Hugo 0.92

Page

params000

Menu items are custom data, not written directly in HTML.

Site Variable

config.json

{
  "baseURL": "http://example.org/",
  "languageCode": "en-us",
  "title": "My New Hugo Site",
  "params": {
    "menu": [
      {
        "title": "Archive",
        "url": "#"
      },
      {
        "title": "Series",
        "url": "#"
      },
      {
        "title": "Tags",
        "url": "#"
      },
      {
        "title": "RSS",
        "url": "#"
      }
    ]
  }
}

Line 5

"params": {
  "menu": [
    {
      "title": "Archive",
      "url": "#"
    },
    {
      "title": "Series",
      "url": "#"
    },
    {
      "title": "Tags",
      "url": "#"
    },
    {
      "title": "RSS",
      "url": "#"
    }
  ]
}

We can store custom data on the params section.

Layout

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>
    <ul class="flex gap-x-2">
      {{ range .Site.Params.Menu }}
      <li>
        <a href="{{ .url }}">{{ .title }}</a>
      </li>
      {{ end }}
    </ul>
  </body>
</html>

Line 11

{{ range .Site.Params.Menu }}
<li>
  <a href="{{ .url }}">{{ .title }}</a>
</li>
{{ end }}
  • range : iterate over a array

Conclusion

  • We can also store custom data by JSON file in the data folder