How <range> in <if>


How can i range in a conditionnal array ?

Here my code where I filter the results of the table by city

{{ $city := .Params.cityName }}
{{ range := .Site.Data.petiteannonce }}
{{ $cityName := .cityName }}
{{ if eq $city $cityName }}

but i just want the first three results.
I’ve tried with {{ range $index, $element := .Site.Data.petiteannonce }} but you know why :slight_smile:

thank you for your help

Try the following:

{{ range := .Site.Data.petiteannonce }}
{{ if .cityName | eq .Params.cityName }}
// do something
{{ end }}
{{ end }}

To be more precise (excuse my french :slight_smile: ) my first block of code is correct but i have all the result.
My issue is i just want the first 3 elements like {{ range first 3 }}

Then try the following:

{{ $cities := where .Site.Data "petiteannonce" "eq" .Params.cityName }}
{{ range first 3 $cities }}
// do something
{{ end }}
{{ end }}

where allows you to filter a collection, e.g. with the equal operator (here eq).
I haven’t tested the code above but it should direct you in the right direction.

For now I have

<first 3 $cities>: error calling first: can't iterate over map[string]interface {}

Could you post an excerpt of your JSON?

Traveling and on phone, so preemptive apologies @digitalcraftsman and @jonathanulco , but can the above be put into a one-liner:

{{ range first 3 (where .Site.Data.petiteannonce "eq" .Params.cityName) }}
Your code
{{ end }}

Here an excerpt of the jSon
and there’s 9 Bordeaux for your test :wink:

Please share a pretty printed version of the JSON next time. Otherwise it’s hard to read. :wink:

I guess .Site.Data.petiteannonce equals the posted array of objects, right?

Give this a try:

{{ range first 3 (where .Site.Data.petiteannonce  "cityName" "eq" .Params.cityName) }}
Your code
{{ end }}

Somehow you have to compare the attribute cityName of the objects with .Params.cityName

1 Like

/bow @digitalcraftsman,
thanks you !