點燈坊

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

Using JSON File to Store Custom Data

Sam Xiao's Avatar 2022-01-19

For site-level custom data, we can store them on the .json file in the data folder.

Version

Hugo 0.92

Page

data000

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

Data

data/menu.json

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

Create a JSON file in the data folder to store custom data.

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.Data.menu.main }}
      <li>
        <a href="{{ .url }}">{{ .title }}</a>
      </li>
      {{ end }}
    </ul>
  </body>
</html>

Line 11

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

Conclusion

  • We can also store custom data on the params section of config.json