Extra category data help

I created a json file to hold some arbitrary extra data related to my categories and I’m running into an issue where I want to pick out just a few select categories to display:

Here’s my attempt to load my json data (this works fine, I do that on the index page), check a particular piece of data (.cssName, one of the properties on my data loaded by getJSON) to see if it matches the categories for this page, then display the description if so.

{{ $projects := getJSON "projects.json" }}
{{ range $projects }}
  {{ if in .Params.categories .cssName }}{{ .description }}{{ end }}
{{ end }}

Hugo doesn’t complain about this formatting, but it also doesn’t show anything. I suspect it’s looking for a Param item within the project data but in fact I want the page-scoped Param that has the page categories in it. How do I get around this scoping issue?

  {{ if in .Params.categories .cssName }}{{ .description }}{{ end }}

Your problem is on this line. Inside of a range where you don’t set a new variable name, the inner loop context changes. So, your attempt to access .Params.categories, which belongs to the Page, doesn’t work. It’s like your code is referencing $project.Params.categories.

Here’s what you want to do. Save the categories to a new variable prior to entering the range loop.

{{ $categories := .Params.categories }}
{{ $projects := getJSON "projects.json" }}
{{ range $projects }}
{{   if in $categories .cssName }}{{ .description }}{{ end }}
{{ end }}

Welcome to Go Templates.

3 Likes

That’s awesome, exactly what I expected and super easy to work around. Thanks!