Need help in getting data from a json file stored in data directory

Hugo noob here. I need to fetch data from a json file stored in the data directory. Say my file is departments.json and has content like

[
    {
        "DepartmentText": "Quality Assurance",
        "DepartmentAbbr": "QA",
        "HasSOP": true,
        "SOPAbbr": "QA",
        "DepartmentIcon": "material/check-decagram"
    },
    {
        "DepartmentText": "Quality Control",
        "DepartmentAbbr": "QC",
        "HasSOP": true,
        "SOPAbbr": "QC",
        "DepartmentIcon": "material/flask-outline"
    },
    {
        "DepartmentText": "Quality Microbiology",
        "DepartmentAbbr": "QM",
        "HasSOP": true,
        "SOPAbbr": "QM",
        "DepartmentIcon": "material/microscope"
    }
]

On a random markdown file, I am trying to access the content with the following

{{ range .Site.Data.departments }}
- {{ .DepartmentText }}
{{ end }}

Exactly like this…

But I am getting this on my site (with hugo server)

image

Should I be directly putting the code on markdown file or should I put this in the layouts/partials or something?

Hi @patrickambrosso

On a random markdown file, I am trying to access the content with the following

{{ range .Site.Data.departments }}
- {{ .DepartmentText }}
{{ end }}

These instructions have to be placed in a layout file, which is the way markdown (and others) files are rendered.

Welsh

Thanks for the quickest reply. That was my error.

Created layouts/shortcodes/departments-list.html

Then put the code

{{ range .Site.Data.departments }}
<ul>
   <li> {{ .DepartmentText }} </li>
</ul>
{{ end }}

into that file.

Then I called this shortcode from my ‘random’ markdown file with {{< departments-list >}} and voila, rendered goodness.

Starting to understand Hugo’s power. Thanks.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.