Hello everyone, I’m new here and I’ve searched far and wide before deciding to write here.
I’m sure I have some kind of misunderstanding about the handling of data inside hugo templates.
I’m trying to build a theme from scratch and wanted to display a series of links to some socials in one page, so I thought I’d use data in json format to create an array of sites I want, with a few details, the base url, the username and a name to display for the site, this is the basic json file I’ve come up with:
we’ll call this file socials.json and it’s saved in the data folder:
$ cat data/socials.json
{
"sites": [
{
"name": "twitter",
"url": "https://twitter.com",
"user": "danixland"
},
{
"name": "reddit",
"url": "https://reddit.com/u",
"user": "danixland"
},
{
"name": "instagram",
"url": "https://www.instagram.com",
"user": "danixland"
}
]
}
I’m not very familiar with json, so I’m not sure if I could have done it differently, but anyway, this makes sense to me and so I rolled with it.
Now to display everything I simply call a partial inside my page, and the partial looks like this:
$ cat home-social-links.html
<div id="home-social-links">
<h3 class="text-only">my socials</h3>
<ul>
{{ range .Site.Data.socials }}
<li>
<a href="{{ .url }}/{{ .user }}">{{ .name }}</a>
</li>
{{ end }}
</ul>
</div>
In the partial I’ve also tried using
{{ range .Site.Data.socials.sites }}
but without success.
The only way I’ve managed to read the file was by calling the partial inside the range iteration and passing the dot to it like this:
$ cat index-baseof.html
[...]
<div id="secondary" class="home-links">
{{ range $.Site.Data.socials }}
{{- partial "home-social-links.html" . -}}
{{ end }}
</div>
[...]
and modify the partial like this:
<div id="home-social-links">
<h3 class="text-only">my socials</h3>
<ul>
{{ range . }}
<li>
<a href="{{ .url }}/{{ .user }}">{{ .name }}</a>
</li>
{{ end }}
</ul>
</div>
And doing so, it magically works, but I don’t understand why it doesn’t when I iterate through it inside the partial file.
Anybody kind enough to go through the logic here so that I can understand what am I missing?!
Thanks a lot in advance