Cannot populate partial with Sanity API

Good morning everyone. I’m trying to build a site on Hugo, and the client wants to be able to add projects to the site as they complete them. To do this, I was trying to set up Sanity CMS. Basically, i need a partial that pulls data from the sanity api to load up the projects they want displayed. I’ll attach some of the code that i have. You can read the api data if you type the endpoint url that i have in the code.

Heres the code from the layout file

	{{ block "projects" . }}
		   {{ $dataJ := getJSON "https://76la3n1i.api.sanity.io/v1/data/query/production?query=*[]{name,description,image}" }}
		   {{ range $dataJ}}
			   {{partial "project.html" }}
			 {{ end }}
		{{ end }}

And heres the partial that i’m trying to load:

 <div>
  <img src="{{.image.asset._ref}}" alt=""">
  <h3">{{ .result.name . }}</h3>
  <p">{{ .result.description}}</p>
</div>

Dont mind the extra quotes on the html elements. Had to add them for this post to display correctly in the forum

Please note, that code blocks need to be wrapped either in backticks manually: ` or within the preformatted text block provided by the </> button in the post UI, otherwise the forum software does not render raw code.

1 Like

ok thanks. sorry i didnt realize that

Regarding your question it appears that your issue is due to the context of $dataJ being lost when trying to access it from a partial.

Either try removing the partial or call the keys of the data file by prepending the $ dollar sign e.g. $.result.name

ok so i took out the partial, and just included the div inside the range. This is what i get

Error: Error building site: failed to render pages: render of “taxonomy” failed: “C:\Users\marcl\OneDrive\Web Development\Krahn Construction\layouts_default\baseof.html:30:36”: execute of template
failed: template: _default/list.html:30:36: executing “projects” at <.name>: can’t evaluate field name in type interface {}

First of all it is a bad idea to keep a Hugo project in Onedrive, Dropbox and other cloud storage providers (there have been posts in this forum from users that ended up with corrupted Git repositories etc)

Second from the error it seems that you do not have that key everywhere in your data set.
Try {{ with .name }}{{ . }}{{ end }}

It is always best to conditionally call keys or parameters in Hugo templates to avoid this type of errors.

ok i didnt realize that about onedrive. only reason i had them there was if my computer quit or something, id always have a backup. Is there another solution for that you’d recommend, or only use git? and thanks for the help. that worked correctly!

you forgot to pass the . dot context.

3 Likes

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