I need to range through local data where .name equals .Name I have in template. How can I achive that?

When I print {{ $.Site.Data.products }} it gives me this:
[map[products:[map[name:Snickers price:39] map[name:Twix price:11] map[name:Mars price:11] map[name:Milky Way price:11]]]]

I tried:

{{ $data := $.Site.Data.products }}
            {{ range $data }}
                {{ range where .products .name "=" .Name }}
                    {{ .price }}
                {{ end }}
            {{ end }}

but no results.

My json file looks like this:

[
  {
    "products": [
      { "name": "Snickers", "price": "39" },
      { "name": "Twix", "price": "11" },
      { "name": "Mars", "price": "11" },
      { "name": "Milky way", "price": "11" }
    ]
  }
]

I do not know what you’re trying to do. What you are trying to do?

if you have /data/products.json as you have pasted, then

{{ $name := "Twix"}}  <!--You can set `{{/* $name := .Name */}}`  ... OR look below-->
{{ range (.Site.Data.products) }}
    {{ range .products }}
        {{ if eq .name $name}} <!-- {{/* if eq .name .Name */}} You can do this too -->
            Name : {{ .name }}<br>
            Price: {{ .price }}
        {{ end }}
    {{ end }}
{{ end}}
1 Like

Are you sure this is the format of your json file? Also what is its name?

because if it lives at data/products.json as it stands you will have to dig through this array of objects to find your products… (products[0].products)

Something like:

{{ $name := .Params.product_name }}
{{ with index site.Data.products 0 }}
  {{ with where .products "Name" $name }}
    {{ range . }}
      {{ .price }}
    {{ end }}
  {{ end }}
{{ end }}

Maybe you can simplify the json file tree?

1 Like

Thank you, I found a solution, a problem was I needed to declare a variable $name before these loops.
My solution:

            {{ $name := .Name }}
            {{ $dataJ := getJSON "data/products.json" }}
            {{ range $dataJ }}
            {{ range .products }}
            {{ if eq .name $name }}
            <strong style="font-size: x-large; color: black">{{ .price }} USD</strong>
            {{ end }}
            {{ end }}
            {{ end }}

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