點燈坊

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

Using range with JSON File

Sam Xiao's Avatar 2022-01-19

We can use range to iterate over an array to render HTML.

Version

Hugo 0.92

Page

range000

Menu items are stored in the Array, 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 Array.

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 in the JSON file

Conclusion

  • range is the looping function in the Go template language. We can use range with Object Array in the JSON file

Reference

Hugo, range