We can use range
to iterate over an array to render HTML.
Version
Hugo 0.92
Page
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 userange
with Object Array in the JSON file