Cannot index slice/array with type string error

Hi all,

Here is my frontmatter:

service:
  enable : true
  service_item:
    # service item loop
    - title : "item title"
      images:
        - url: "images/abc.png"
          alt: "abc"          
        - url: "images/xyz.png"
          alt: "xyz"
      content: "content here"

The service item loop is working fine, but I just cant figure out how to access the values of the images array. When testing like this:

{{ range .images }}
  {{ . }}  
{{ end }}

I get the following output which looks the way I’d want it:

map
  [
    alt:abc 
    url:images/abc.png 
  ]
map
  [
    alt:xyz 
    url:images/xyz.png 
  ]

Next I tried range and retrieve via index:

{{ with .images }}
{{ range . }}
    {{ $image_key_value := (index . "url") }}
    {{ printf "Image path: %s<br />" $image_key_value | safeHTML }}  
{{ end }}
{{ end }}

Which threw this error:

execute of template failed: template: partials/service.html:23:36: executing "partials/service.html" at <index . "url">: error calling index: cannot index slice/array with type string

Any ideas on how to best get to this nested data? Is there a better way to structure my frontmatter? This should be an array, not sure why it’s seen as a string… I just need to get to the alt and url values.

A related thread seems to cover exactly this issue but without the string error:

Thanks!

You can access it directly like this:

{{ range .images }}
  {{ .url }} {{ .alt }}  
{{ end }}

thanks, but that was the first thing I tried. Throws this error:

executing "partials/service.html" at <.url>: can't evaluate field url in type interface {}

show me the full code how did you loop the service item.

Also, make sure each service item has images property.

Thanks pamubay, your last comment got me on the right track: I still had an images array definition in another service item that had a slightly different structure, now that they are all the same it’s working perfect! Thanks!

1 Like

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